Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

fix(payload): harden connector against unknown enum variants and non-JSON error bodies (#13256)

Sai Harsha Vardhan276de225f426
diff --git a/crates/hyperswitch_connectors/src/connectors/payload.rs b/crates/hyperswitch_connectors/src/connectors/payload.rs
index 5a614a9cd0..3b0e031ec6 100644
--- a/crates/hyperswitch_connectors/src/connectors/payload.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payload.rs
@@ -50,6 +50,7 @@ use hyperswitch_interfaces::{
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
+ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
disputes::DisputePayload,
errors,
events::connector_api_logs::ConnectorEvent,
@@ -249,27 +250,55 @@ impl ConnectorCommon for Payload {
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- let response: responses::PayloadErrorResponse = res
- .response
- .parse_struct("PayloadErrorResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ if res.response.is_empty() {
+ return Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: NO_ERROR_CODE.to_string(),
+ message: NO_ERROR_MESSAGE.to_string(),
+ reason: None,
+ attempt_status: None,
+ connector_transaction_id: None,
+ connector_response_reference_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ });
+ }
- event_builder.map(|i| i.set_response_body(&response));
- router_env::logger::info!(connector_response=?response);
+ let response: Result<responses::PayloadErrorResponse, _> =
+ res.response.parse_struct("PayloadErrorResponse");
- Ok(ErrorResponse {
- status_code: res.status_code,
- code: response.error_type,
- message: response.error_description.clone(),
- reason: Some(response.error_description),
- attempt_status: None,
- connector_transaction_id: None,
- connector_response_reference_id: None,
- network_advice_code: None,
- network_decline_code: None,
- network_error_message: None,
- connector_metadata: None,
- })
+ match response {
+ Ok(response) => {
+ 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.error_type,
+ message: response.error_description.clone(),
+ reason: Some(response.error_description),
+ attempt_status: None,
+ connector_transaction_id: None,
+ connector_response_reference_id: None,
+ network_advice_code: None,
+ network_decline_code: None,
+ network_error_message: None,
+ connector_metadata: None,
+ })
+ }
+ Err(error_msg) => {
+ if let Some(event) = event_builder {
+ event.set_error(serde_json::json!({
+ "error": "Error response parsing failed",
+ "status_code": res.status_code
+ }));
+ }
+ router_env::logger::error!(deserialization_error =? error_msg);
+ utils::handle_json_response_deserialization_failure(res, "payload")
+ }
+ }
}
}
@@ -1101,7 +1130,8 @@ impl webhooks::IncomingWebhook for Payload {
| responses::PayloadWebhooksTrigger::ChargebackReversal
| responses::PayloadWebhooksTrigger::PaymentActivationStatus
| responses::PayloadWebhooksTrigger::PaymentLinkStatus
- | responses::PayloadWebhooksTrigger::Refund => {
+ | responses::PayloadWebhooksTrigger::Refund
+ | responses::PayloadWebhooksTrigger::Unknown => {
Err(errors::ConnectorError::WebhooksNotImplemented.into())
}
}
@@ -1112,6 +1142,10 @@ impl webhooks::IncomingWebhook for Payload {
request: &webhooks::IncomingWebhookRequestDetails<'_>,
snapshot: Option<&webhooks::WebhookContext>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
+ if request.body.is_empty() {
+ return Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported);
+ }
+
let webhook_body: responses::PayloadWebhookEvent =
request.body.parse_struct("PayloadWebhookEvent").switch()?;
diff --git a/crates/hyperswitch_connectors/src/connectors/payload/responses.rs b/crates/hyperswitch_connectors/src/connectors/payload/responses.rs
index d42fdd3411..be99cb614d 100644
--- a/crates/hyperswitch_connectors/src/connectors/payload/responses.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payload/responses.rs
@@ -11,6 +11,8 @@ pub enum PayloadPaymentStatus {
Processing,
Rejected,
Voided,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -28,11 +30,12 @@ pub struct PayloadPostCaptureVoidResponse(pub PayloadPaymentsResponse);
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum AvsResponse {
- Unknown,
NoMatch,
Zip,
Street,
StreetAndZip,
+ #[serde(other)]
+ Unknown,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -67,15 +70,8 @@ pub enum RefundStatus {
#[default]
Processing,
Rejected,
-}
-
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
-pub struct RefundsLedger {
- pub amount: f64,
- #[serde(rename = "assoc_transaction_id")]
- pub associated_transaction_id: String, // Connector transaction id
- #[serde(rename = "id")]
- pub ledger_id: Secret<String>,
+ #[serde(other)]
+ Unknown,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
@@ -83,7 +79,7 @@ pub struct PayloadRefundResponse {
pub amount: Option<f64>,
#[serde(rename = "id")]
pub transaction_id: String,
- pub ledger: Vec<RefundsLedger>,
+ pub ledger: Option<serde_json::Value>,
#[serde(rename = "payment_method_id")]
pub connector_payment_method_id: Option<Secret<String>>,
pub processing_id: Option<Secret<String>>,
@@ -128,6 +124,8 @@ pub enum PayloadWebhooksTrigger {
TransactionOperation,
#[serde(rename = "transaction:operation:clear")]
TransactionOperationClear,
+ #[serde(other)]
+ Unknown,
}
impl PayloadWebhooksTrigger {
pub fn as_str(&self) -> &'static str {
@@ -151,6 +149,7 @@ impl PayloadWebhooksTrigger {
Self::ChargebackReversal => "chargeback_reversal",
Self::TransactionOperation => "transaction:operation",
Self::TransactionOperationClear => "transaction:operation:clear",
+ Self::Unknown => "unknown",
}
}
}
@@ -180,9 +179,9 @@ pub struct PayloadEventDetails {
pub struct PayloadPaymentMethodResponse {
pub id: String, // Payment method ID (pm_xxx)
pub account_holder: Option<Secret<String>>,
- pub customer_id: String, // Same as account_id sent
- pub verification_status: PayloadVerificationStatus,
- pub status: String, // "active"
+ pub customer_id: Option<String>, // Same as account_id sent
+ pub verification_status: Option<PayloadVerificationStatus>,
+ pub status: Option<String>, // "active"
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
diff --git a/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs
index a7152956bf..b4a4399bdd 100644
--- a/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payload/transformers.rs
@@ -462,15 +462,24 @@ impl TryFrom<&PayloadRouterData<&PaymentsAuthorizeRouterData>>
}
}
-impl From<responses::PayloadPaymentStatus> for common_enums::AttemptStatus {
- fn from(item: responses::PayloadPaymentStatus) -> Self {
- match item {
- responses::PayloadPaymentStatus::Authorized => Self::Authorized,
- responses::PayloadPaymentStatus::Processed => Self::Charged,
- responses::PayloadPaymentStatus::Processing => Self::Pending,
- responses::PayloadPaymentStatus::Rejected
- | responses::PayloadPaymentStatus::Declined => Self::Failure,
- responses::PayloadPaymentStatus::Voided => Self::Voided,
+fn get_payload_attempt_status(
+ status: responses::PayloadPaymentStatus,
+ prev_status: common_enums::AttemptStatus,
+) -> common_enums::AttemptStatus {
+ match status {
+ responses::PayloadPaymentStatus::Authorized => common_enums::AttemptStatus::Authorized,
+ responses::PayloadPaymentStatus::Processed => common_enums::AttemptStatus::Charged,
+ responses::PayloadPaymentStatus::Processing => common_enums::AttemptStatus::Pending,
+ responses::PayloadPaymentStatus::Rejected | responses::PayloadPaymentStatus::Declined => {
+ common_enums::AttemptStatus::Failure
+ }
+ responses::PayloadPaymentStatus::Voided => common_enums::AttemptStatus::Voided,
+ responses::PayloadPaymentStatus::Unknown => {
+ router_env::logger::warn!(
+ "Payload returned unknown payment status; retaining previous status {:?}",
+ prev_status
+ );
+ prev_status
}
}
}
@@ -512,7 +521,7 @@ where
(true, responses::PayloadPaymentStatus::Authorized) => {
enums::AttemptStatus::Pending
}
- _ => enums::AttemptStatus::from(response.status),
+ _ => get_payload_attempt_status(response.status, item.data.status),
};
let mandate_reference = is_mandate_payment
@@ -674,6 +683,12 @@ impl
| responses::PayloadPaymentStatus::Processed => {
common_enums::PostCaptureVoidStatus::Failed
}
+ responses::PayloadPaymentStatus::Unknown => {
+ router_env::logger::warn!(
+ "Payload returned unknown payment status for post-capture-void; defaulting to pending"
+ );
+ common_enums::PostCaptureVoidStatus::Pending
+ }
};
let description = post_capture_void_status
@@ -718,12 +733,22 @@ impl<F> TryFrom<&PayloadRouterData<&RefundsRouterData<F>>> for requests::Payload
}
}
-impl From<responses::RefundStatus> for enums::RefundStatus {
- fn from(item: responses::RefundStatus) -> Self {
- match item {
- responses::RefundStatus::Processed => Self::Success,
- responses::RefundStatus::Processing => Self::Pending,
- responses::RefundStatus::Declined | responses::RefundStatus::Rejected => Self::Failure,
+fn get_payload_refund_status(
+ status: responses::RefundStatus,
+ prev_refund_status: enums::RefundStatus,
+) -> enums::RefundStatus {
+ match status {
+ responses::RefundStatus::Processed => enums::RefundStatus::Success,
+ responses::RefundStatus::Processing => enums::RefundStatus::Pending,
+ responses::RefundStatus::Declined | responses::RefundStatus::Rejected => {
+ enums::RefundStatus::Failure
+ }
+ responses::RefundStatus::Unknown => {
+ router_env::logger::warn!(
+ "Payload returned unknown refund status; retaining previous refund status {:?}",
+ prev_refund_status
+ );
+ prev_refund_status
}
}
}
@@ -735,10 +760,12 @@ impl TryFrom<RefundsResponseRouterData<Execute, responses::PayloadRefundResponse
fn try_from(
item: RefundsResponseRouterData<Execute, responses::PayloadRefundResponse>,
) -> Result<Self, Self::Error> {
+ let refund_status =
+ get_payload_refund_status(item.response.status, item.data.request.refund_status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ refund_status,
}),
..item.data
})
@@ -752,10 +779,12 @@ impl TryFrom<RefundsResponseRouterData<RSync, responses::PayloadRefundResponse>>
fn try_from(
item: RefundsResponseRouterData<RSync, responses::PayloadRefundResponse>,
) -> Result<Self, Self::Error> {
+ let refund_status =
+ get_payload_refund_status(item.response.status, item.data.request.refund_status);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ refund_status,
}),
..item.data
})
@@ -795,6 +824,12 @@ impl From<responses::PayloadWebhooksTrigger> for IncomingWebhookEvent {
| responses::PayloadWebhooksTrigger::TransactionOperationClear => {
Self::EventNotSupported
}
+ responses::PayloadWebhooksTrigger::Unknown => {
+ router_env::logger::warn!(
+ "Unknown payload webhook trigger received; acknowledging without processing"
+ );
+ Self::EventNotSupported
+ }
}
}
}
@@ -830,7 +865,8 @@ impl TryFrom<responses::PayloadWebhooksTrigger> for responses::PayloadPaymentSta
| responses::PayloadWebhooksTrigger::PaymentLinkStatus
| responses::PayloadWebhooksTrigger::ProcessingStatus
| responses::PayloadWebhooksTrigger::TransactionOperation
- | responses::PayloadWebhooksTrigger::TransactionOperationClear => {
+ | responses::PayloadWebhooksTrigger::TransactionOperationClear
+ | responses::PayloadWebhooksTrigger::Unknown => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}