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
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
fix(core): add validation for card expiry month, expiry year and card cvc (#1416)
Prasunna Soppac40617aea66e
diff --git a/crates/cards/src/lib.rs b/crates/cards/src/lib.rsindex d8aedc36e1..52e62e0912 100644--- a/crates/cards/src/lib.rs+++ b/crates/cards/src/lib.rs@@ -18,7 +18,7 @@ pub struct CardSecurityCode(StrongSecret<u16>);impl TryFrom<u16> for CardSecurityCode {type Error = error_stack::Report<errors::ValidationError>;fn try_from(csc: u16) -> Result<Self, Self::Error> {- if (100..=9999).contains(&csc) {+ if (1..=9999).contains(&csc) {Ok(Self(StrongSecret::new(csc)))} else {Err(report!(errors::ValidationError::InvalidValue {diff --git a/crates/cards/tests/basic.rs b/crates/cards/tests/basic.rsindex a2e01d6406..2fdfa1354c 100644--- a/crates/cards/tests/basic.rs+++ b/crates/cards/tests/basic.rs@@ -10,7 +10,7 @@ fn test_card_security_code() {let valid_card_security_code = CardSecurityCode::try_from(1234).unwrap();// will panic on unwrap- let invalid_card_security_code = CardSecurityCode::try_from(12);+ let invalid_card_security_code = CardSecurityCode::try_from(00);assert_eq!(*valid_card_security_code.peek(), 1234);assert!(invalid_card_security_code.is_err());@@ -21,7 +21,7 @@ fn test_card_security_code() {let derialized = serde_json::from_str::<CardSecurityCode>(&serialized).unwrap();assert_eq!(*derialized.peek(), 1234);- let invalid_deserialization = serde_json::from_str::<CardSecurityCode>("12");+ let invalid_deserialization = serde_json::from_str::<CardSecurityCode>("00");assert!(invalid_deserialization.is_err());}@@ -76,24 +76,24 @@ fn test_card_expiration() {let curr_year = u16::try_from(curr_date.year()).expect("valid year");// no panic- let card_exp = CardExpiration::try_from((3, curr_year + 1)).unwrap();+ let card_exp = CardExpiration::try_from((3, curr_year)).unwrap();// will panic on unwrap- let invalid_card_exp = CardExpiration::try_from((13, curr_year + 1));+ let invalid_card_exp = CardExpiration::try_from((13, curr_year));assert_eq!(*card_exp.get_month().peek(), 3);- assert_eq!(*card_exp.get_year().peek(), curr_year + 1);+ assert_eq!(*card_exp.get_year().peek(), curr_year);assert!(card_exp.is_expired().unwrap());assert!(invalid_card_exp.is_err());let serialized = serde_json::to_string(&card_exp).unwrap();- let expected_string = format!(r#"{{"month":{},"year":{}}}"#, 3, curr_year + 1);+ let expected_string = format!(r#"{{"month":{},"year":{}}}"#, 3, curr_year);assert_eq!(serialized, expected_string);let derialized = serde_json::from_str::<CardExpiration>(&serialized).unwrap();assert_eq!(*derialized.get_month().peek(), 3);- assert_eq!(*derialized.get_year().peek(), curr_year + 1);+ assert_eq!(*derialized.get_year().peek(), curr_year);let invalid_serialized_string = r#"{"month":13,"year":123}"#;let invalid_deserialization = serde_json::from_str::<CardExpiration>(invalid_serialized_string);diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex b29d89a381..2795ad251b 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -433,6 +433,72 @@ pub fn validate_request_amount_and_amount_to_capture(}}+#[instrument(skip_all)]+pub fn validate_card_data(+ payment_method_data: Option<api::PaymentMethodData>,+) -> CustomResult<(), errors::ApiErrorResponse> {+ if let Some(api::PaymentMethodData::Card(card)) = payment_method_data {+ let cvc = card.card_cvc.peek().to_string();+ if cvc.len() < 3 || cvc.len() > 4 {+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "Invalid card_cvc length".to_string()+ }))?+ }+ let card_cvc = cvc.parse::<u16>().into_report().change_context(+ errors::ApiErrorResponse::InvalidDataValue {+ field_name: "card_cvc",+ },+ )?;+ ::cards::CardSecurityCode::try_from(card_cvc).change_context(+ errors::ApiErrorResponse::PreconditionFailed {+ message: "Invalid Card CVC".to_string(),+ },+ )?;++ let exp_month = card+ .card_exp_month+ .peek()+ .to_string()+ .parse::<u8>()+ .into_report()+ .change_context(errors::ApiErrorResponse::InvalidDataValue {+ field_name: "card_exp_month",+ })?;+ let month = ::cards::CardExpirationMonth::try_from(exp_month).change_context(+ errors::ApiErrorResponse::PreconditionFailed {+ message: "Invalid Expiry Month".to_string(),+ },+ )?;+ let mut year_str = card.card_exp_year.peek().to_string();+ if year_str.len() == 2 {+ year_str = format!("20{}", year_str);+ }+ let exp_year = year_str.parse::<u16>().into_report().change_context(+ errors::ApiErrorResponse::InvalidDataValue {+ field_name: "card_exp_year",+ },+ )?;+ let year = ::cards::CardExpirationYear::try_from(exp_year).change_context(+ errors::ApiErrorResponse::PreconditionFailed {+ message: "Invalid Expiry Year".to_string(),+ },+ )?;++ let card_expiration = ::cards::CardExpiration { month, year };+ let is_expired = card_expiration.is_expired().change_context(+ errors::ApiErrorResponse::PreconditionFailed {+ message: "Invalid card data".to_string(),+ },+ )?;+ if is_expired {+ Err(report!(errors::ApiErrorResponse::PreconditionFailed {+ message: "Card Expired".to_string()+ }))?+ }+ }+ Ok(())+}+pub fn validate_mandate(req: impl Into<api::MandateValidationFields>,is_confirm_operation: bool,diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 2ee8b49962..8e6eb78f35 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -122,6 +122,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pafield_name: "browser_info",})?;+ helpers::validate_card_data(request.payment_method_data.clone())?;+let customer_details = helpers::get_customer_details_from_request(request);let token = token.or_else(|| payment_attempt.payment_token.clone());diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex a4f20e96f8..44f7c0a863 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -444,6 +444,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreateexpected_format: "amount_to_capture lesser than amount".to_string(),})?;+ helpers::validate_card_data(request.payment_method_data.clone())?;+helpers::validate_payment_method_fields_present(request)?;let payment_id = core_utils::get_or_generate_id("payment_id", &given_payment_id, "pay")?;diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rsindex 01e5498db1..1d7f6cce49 100644--- a/crates/router/src/core/payments/operations/payment_update.rs+++ b/crates/router/src/core/payments/operations/payment_update.rs@@ -63,6 +63,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa.map(ForeignInto::foreign_into).or(payment_intent.setup_future_usage);+ helpers::validate_card_data(request.payment_method_data.clone())?;+helpers::validate_payment_status_against_not_allowed_statuses(&payment_intent.status,&[