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
test(cypress): add payment response hash coverage (#12226)
HS-QUALIBOT35f056f632d2
diff --git a/cypress-tests/cypress.config.js b/cypress-tests/cypress.config.jsindex aa83fe13d7..fcde576b7a 100644--- a/cypress-tests/cypress.config.js+++ b/cypress-tests/cypress.config.js@@ -1,5 +1,6 @@import { defineConfig } from "cypress";import mochawesome from "cypress-mochawesome-reporter/plugin.js";+import crypto from "crypto";import fs from "fs";import { getTimeoutMultiplier } from "./cypress/utils/RequestBodyUtils.js";@@ -33,6 +34,18 @@ export default defineConfig({console.log(message);return null;},+ computeHmac: ({ key, message, algorithm = "sha512" }) => {+ if (!key || !message) {+ throw new Error(+ `computeHmac: 'key' and 'message' are required (got key=${!!key}, message=${!!message})`+ );+ }+ const signature = crypto+ .createHmac(algorithm, key)+ .update(message)+ .digest("hex");+ return signature;+ },});on("after:spec", (spec, results) => {// Clean up resources after each specdiff --git a/cypress-tests/cypress/e2e/configs/Payment/Utils.js b/cypress-tests/cypress/e2e/configs/Payment/Utils.jsindex 0957aa143a..f798740a9b 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Utils.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Utils.js@@ -603,6 +603,7 @@ export const CONNECTOR_LISTS = {AUTH_SERVICE_ELIGIBILITY: ["stripe", "cybersource"],STEP_UP_AUTH: ["cybersource"],PARTIAL_AUTH: ["nuvei", "checkout", "worldpay", "worldpayvantiv"],+ PAYMENT_RESPONSE_HASH: ["stripe"],MULTIPLE_CAPTURE: ["adyen", "checkout"],USE_BILLING_AS_PAYMENT_METHOD_BILLING: ["bankofamerica"],MIT_WITH_LIMITED_CARD_DATA: ["peachpayments"],diff --git a/cypress-tests/cypress/e2e/spec/Payment/52-PaymentResponseHash.cy.js b/cypress-tests/cypress/e2e/spec/Payment/52-PaymentResponseHash.cy.jsnew file mode 100644index 0000000000..edad3b2146--- /dev/null+++ b/cypress-tests/cypress/e2e/spec/Payment/52-PaymentResponseHash.cy.js@@ -0,0 +1,202 @@+import * as fixtures from "../../../fixtures/imports";+import State from "../../../utils/State";+import getConnectorDetails, * as utils from "../../configs/Payment/Utils";+import { setup3DSPayment } from "../../../utils/paymentHelpers";++let globalState;++describe("Card - Payment Response Hash flow test", () => {+ // Gate variable: set to false when the connector does not support+ // payment-response-hash or when the merchant has the feature disabled.+ // Used in beforeEach to skip every test in this describe block.+ let shouldContinue = true;++ before("seed global state and check account config", function () {+ return cy.task("getGlobalState").then((state) => {+ globalState = new State(state);+ // Check if the current connector supports the payment response hash feature+ // This gate ensures the test only runs for connectors explicitly configured+ // with PAYMENT_RESPONSE_HASH support (currently only Stripe)+ if (+ !utils.CONNECTOR_LISTS.INCLUDE.PAYMENT_RESPONSE_HASH.includes(+ globalState.get("connectorId")+ )+ ) {+ shouldContinue = false;+ return;+ }+ return cy.fetchPaymentResponseHashConfig(globalState).then(() => {+ const enablePaymentResponseHash = globalState.get(+ "enablePaymentResponseHash"+ );+ if (!enablePaymentResponseHash) {+ cy.task(+ "cli_log",+ "enable_payment_response_hash is false - skipping spec"+ );+ shouldContinue = false;+ }+ });+ });+ });++ beforeEach(function () {+ if (!shouldContinue) {+ this.skip();+ }+ });++ after("flush global state", () => {+ cy.task("setGlobalState", globalState.data);+ });++ context("No3DS Auto-Capture - Verify Payment Response Hash Config", () => {+ it("create payment intent -> confirm payment -> verify payment response hash", () => {+ // Per-step gate variable: tracks whether the preceding API call+ // succeeded so that subsequent steps can be skipped gracefully when+ // a connector does not support the No3DS auto-capture flow.+ let stepContinue = true;++ cy.step("create payment intent", () => {+ const data = getConnectorDetails(globalState.get("connectorId"))[+ "card_pm"+ ]["PaymentIntent"];++ // Create a payment intent with no-3DS authentication and automatic capture+ // "no_three_ds": disables 3-D Secure authentication for a frictionless card flow+ // "automatic": captures the authorized amount immediately without manual capture step+ // globalState: shared state object for persisting payment data across test steps+ cy.createPaymentIntentTest(+ fixtures.createPaymentBody,+ data,+ "no_three_ds", // authentication type: no 3-D Secure challenge required+ "automatic", // capture method: auto-capture (immediate settlement)+ globalState // shared mutable state for cross-step data persistence+ );++ if (!utils.should_continue_further(data)) {+ stepContinue = false;+ }+ });++ cy.step("confirm payment", () => {+ if (!stepContinue) {+ cy.task("cli_log", "Skipping step: confirm payment");+ return;+ }++ const data = getConnectorDetails(globalState.get("connectorId"))[+ "card_pm"+ ]["No3DSAutoCapture"];++ cy.confirmCallTest(fixtures.confirmBody, data, true, globalState);++ if (!utils.should_continue_further(data)) {+ stepContinue = false;+ }+ });++ cy.step("retrieve payment", () => {+ if (!stepContinue) {+ cy.task("cli_log", "Skipping step: retrieve payment");+ return;+ }++ cy.retrievePaymentCallTest({ globalState });+ });++ cy.step("verify payment response hash", () => {+ if (!stepContinue) {+ cy.task("cli_log", "Skipping step: verify payment response hash");+ return;+ }++ // Verify payment response hash is enabled in business profile config+ cy.assertPaymentResponseHashEnabled(globalState);+ });+ });+ });++ context("3DS Auto-Capture - Verify Redirect Signature", () => {+ it("setup 3DS -> verify redirect signature", () => {+ // Setup 3DS payment flow without redirection to test signature verification+ // globalState: shared state object for test data persistence+ // includeRedirection: false - skips the actual browser redirection to focus on signature validation+ // fixtures: test data fixtures for payment setup+ setup3DSPayment(globalState, { includeRedirection: false, fixtures });++ cy.step("verify redirect signature", () => {+ // Assert that redirect URL was captured before attempting signature verification+ // This prevents silent passes when captureRedirectReturnUrl fails+ expect(+ globalState.get("redirectReturnUrl"),+ "redirectReturnUrl must be captured from 3DS setup"+ ).to.exist.and.not.be.empty;++ cy.verifyRedirectSignature(globalState);+ });+ });+ });++ context("3DS Auto-Capture - Compute and Verify Redirect Signature", () => {+ it("setup 3DS -> compute HMAC and compare with redirect signature", () => {+ // Setup 3DS payment flow to test HMAC computation and signature comparison+ // globalState: shared state object for test data persistence+ // includeRedirection: false - skips browser redirection to focus on HMAC computation logic+ // fixtures: test data fixtures for payment setup+ setup3DSPayment(globalState, { includeRedirection: false, fixtures });++ cy.step("compute and verify redirect signature", () => {+ if (!globalState.get("_setup3DSContinue")) {+ cy.task(+ "cli_log",+ "Skipping step: compute and verify redirect signature"+ );+ return;+ }++ cy.computeAndVerifyRedirectSignature(globalState);+ });+ });+ });++ context("3DS Auto-Capture - Failure Scenarios for Invalid Signatures", () => {+ it("setup 3DS -> compute HMAC -> verify tampered and wrong-key signatures fail", () => {+ // Setup 3DS payment flow for testing tampered and wrong-key signature scenarios+ // globalState: shared state object for test data persistence+ // includeRedirection: false - skips browser redirection to test signature validation failures+ // fixtures: test data fixtures for payment setup+ setup3DSPayment(globalState, { includeRedirection: false, fixtures });++ cy.step("compute and verify redirect signature", () => {+ if (!globalState.get("_setup3DSContinue")) {+ cy.task(+ "cli_log",+ "Skipping step: compute and verify redirect signature"+ );+ return;+ }++ cy.computeAndVerifyRedirectSignature(globalState);+ });++ cy.step("verify tampered signature fails", () => {+ if (!globalState.get("_setup3DSContinue")) {+ cy.task("cli_log", "Skipping step: verify tampered signature fails");+ return;+ }++ cy.verifyTamperedSignatureFails(globalState);+ });++ cy.step("verify wrong-key signature fails", () => {+ if (!globalState.get("_setup3DSContinue")) {+ cy.task("cli_log", "Skipping step: verify wrong-key signature fails");+ return;+ }++ cy.verifyWrongKeySignatureFails(globalState);+ });+ });+ });+});diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex 164eb7047c..c87f20300a 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -489,6 +489,18 @@ function cleanupProcessedRequestIds(globalState.set("requestIds", remainingRequestIds);}+const EXPECTED_ALGORITHM = "HMAC-SHA512";+const HASH_ALGO = "sha512";+const SIGNATURE_HEX_LENGTH = 128;++function resolveAlgorithm(signatureAlgorithm) {+ expect(+ signatureAlgorithm,+ `signature_algorithm must be ${EXPECTED_ALGORITHM}`+ ).to.equal(EXPECTED_ALGORITHM);+ return HASH_ALGO;+}+function logRequestId(xRequestId) {if (xRequestId) {cy.task("cli_log", "x-request-id -> " + xRequestId);@@ -2758,6 +2770,12 @@ Cypress.Commands.add(expect(resData.body[key], [key]).to.deep.equal(response.body[key]);}} else if (response.status === 200) {+ if (response.body.next_action?.redirect_to_url) {+ globalState.set(+ "nextActionUrl",+ response.body.next_action.redirect_to_url+ );+ }globalState.set("paymentID", paymentIntentID);updateConnectorState(globalState, response.body.connector);globalState.set(@@ -9515,6 +9533,340 @@ Cypress.Commands.add("retrieveNonExistentPaymentLinkTest", (globalState) => {});});+/**+ * Fetches merchant account config and stores payment response hash settings in globalState.+ * Also skips the suite if enable_payment_response_hash is false/absent.+ *+ * The backend falls back to merchant-account-level settings when business profile+ * fields are unset, so we fetch from the merchant account endpoint to reliably+ * read the payment_response_hash configuration.+ *+ * @param {Object} globalState - The global state object+ */+Cypress.Commands.add("fetchPaymentResponseHashConfig", (globalState) => {+ const merchantId = globalState.get("merchantId");+ const apiKey = globalState.get("adminApiKey");+ const baseUrl = globalState.get("baseUrl");+ const url = `${baseUrl}/accounts/${merchantId}`;++ cy.request({+ method: "GET",+ url,+ headers: {+ "Content-Type": "application/json",+ "api-key": apiKey,+ },+ failOnStatusCode: false,+ }).then((response) => {+ if (!response || response.status !== 200) {+ cy.task(+ "cli_log",+ `Failed to fetch merchant account config (status: ${response?.status}) - skipping spec`+ );+ return;+ }++ const enablePaymentResponseHash =+ response.body.enable_payment_response_hash;+ const paymentResponseHashKey = response.body.payment_response_hash_key;++ if (!enablePaymentResponseHash) {+ cy.task(+ "cli_log",+ "enable_payment_response_hash is false/absent - skipping spec"+ );+ // Explicitly store false so the negative test can distinguish+ // "confirmed disabled" from "fetch failed"+ globalState.set("enablePaymentResponseHash", false);+ return;+ }++ // Validate that the hash key is present and non-empty+ // A null or empty key would cause cryptic Node crypto errors downstream+ if (+ typeof paymentResponseHashKey !== "string" ||+ paymentResponseHashKey.length === 0+ ) {+ throw new Error(+ "fetchPaymentResponseHashConfig: enable_payment_response_hash is true but payment_response_hash_key is null or empty"+ );+ }++ globalState.set("paymentResponseHashKey", paymentResponseHashKey);+ globalState.set("enablePaymentResponseHash", true);++ cy.task(+ "cli_log",+ `Merchant account config verified - enable_payment_response_hash: true, key length: ${paymentResponseHashKey.length}`+ );+ });+});++/**+ * Verifies that the payment response hash feature is properly configured on the business profile.+ *+ * The payment_response_hash feature adds HMAC signatures to redirect URLs (as+ * `signature` and `signature_algorithm` query params) and to outgoing webhook headers+ * (as `Stripe-Signature` or `X-Webhook-Signature`). It does NOT add a field to the+ * payment response JSON body.+ *+ * This command uses the values already stored in globalState by the before hook+ * (enablePaymentResponseHash and paymentResponseHashKey) — it does NOT re-fetch the+ * business profile API.+ *+ * @param {Object} globalState - The global state object+ */+Cypress.Commands.add("assertPaymentResponseHashEnabled", (globalState) => {+ const enablePaymentResponseHash = globalState.get(+ "enablePaymentResponseHash"+ );+ const hashKey = globalState.get("paymentResponseHashKey");++ expect(+ enablePaymentResponseHash,+ "enable_payment_response_hash should be true"+ ).to.equal(true);++ expect(hashKey, "payment_response_hash_key should exist").to.be.a("string")+ .and.not.be.empty;++ cy.task(+ "cli_log",+ `Payment response hash config verified - enable_payment_response_hash: true, key length: ${hashKey.length}`+ );+});++Cypress.Commands.add("verifyRedirectSignature", (globalState) => {+ const redirectUrl =+ globalState.get("redirectReturnUrl") || globalState.get("nextActionUrl");++ if (!redirectUrl) {+ cy.task(+ "cli_log",+ "No redirect URL in global state - redirect signature verification not applicable for this flow"+ );+ return;+ }++ const urlObj = new URL(redirectUrl);+ const signature = urlObj.searchParams.get("signature");+ const signatureAlgorithm = urlObj.searchParams.get("signature_algorithm");++ expect(signature, "signature should exist in redirect URL").to.be.a("string")+ .and.not.be.empty;++ // Validate hex format: exactly 128 lowercase hex characters+ expect(+ signature,+ `signature must be a valid ${SIGNATURE_HEX_LENGTH}-char hex string`+ ).to.match(/^[0-9a-f]{128}$/);++ expect(+ signatureAlgorithm,+ "signature_algorithm must be HMAC-SHA512"+ ).to.equal(EXPECTED_ALGORITHM);++ cy.task(+ "cli_log",+ `Redirect signature verified - algorithm: ${signatureAlgorithm}, signature length: ${signature.length}, hex format: valid`+ );+});++Cypress.Commands.add("computeAndVerifyRedirectSignature", (globalState) => {+ const hashKey = globalState.get("paymentResponseHashKey");+ expect(+ hashKey,+ "payment_response_hash_key should exist in global state"+ ).to.be.a("string").and.not.be.empty;++ const redirectUrl =+ globalState.get("redirectReturnUrl") || globalState.get("nextActionUrl");++ if (!redirectUrl) {+ cy.task(+ "cli_log",+ "No redirect URL in global state - HMAC computation not applicable for this flow"+ );+ return;+ }++ const urlObj = new URL(redirectUrl);+ const signature = urlObj.searchParams.get("signature");+ const signatureAlgorithm = urlObj.searchParams.get("signature_algorithm");++ expect(signature, "signature should exist in redirect URL").to.be.a("string")+ .and.not.be.empty;+ expect(+ signatureAlgorithm,+ "signature_algorithm must be HMAC-SHA512"+ ).to.equal(EXPECTED_ALGORITHM);++ const signatureParams = [];+ urlObj.searchParams.forEach((value, key) => {+ if (key !== "signature" && key !== "signature_algorithm") {+ signatureParams.push([key, value]);+ }+ });++ signatureParams.sort((a, b) => {+ if (a[0] < b[0]) return -1;+ if (a[0] > b[0]) return 1;+ return 0;+ });+ const signingPayload = signatureParams.map(([k, v]) => `${k}=${v}`).join("&");+ const algorithm = resolveAlgorithm(signatureAlgorithm);++ cy.task("computeHmac", {+ key: hashKey,+ message: signingPayload,+ algorithm,+ }).then((computedSignature) => {+ expect(computedSignature, "HMAC computation should not return null").to.not+ .be.null;++ expect(+ computedSignature,+ "Computed HMAC signature should match the received signature"+ ).to.equal(signature);++ globalState.set("computedSigningPayload", signingPayload);+ globalState.set("computedSignature", computedSignature);++ cy.task(+ "cli_log",+ `HMAC computed and verified (algorithm: ${EXPECTED_ALGORITHM}) - signing payload: ${signingPayload.substring(0, 80)}..., signature match: YES`+ );+ });+});++Cypress.Commands.add("verifyTamperedSignatureFails", (globalState) => {+ const computedSignature = globalState.get("computedSignature");+ const hashKey = globalState.get("paymentResponseHashKey");+ const signingPayload = globalState.get("computedSigningPayload");++ expect(+ computedSignature,+ "computedSignature must exist from prior step - ensure computeAndVerifyRedirectSignature was called first"+ ).to.be.a("string").and.not.be.empty;++ expect(+ hashKey,+ "payment_response_hash_key must exist in global state - ensure proper test setup"+ ).to.be.a("string").and.not.be.empty;++ expect(+ signingPayload,+ "computedSigningPayload must exist from prior step - ensure computeAndVerifyRedirectSignature was called first"+ ).to.be.a("string").and.not.be.empty;++ const algorithm = HASH_ALGO;+ const tamperedPayload = signingPayload + "&tampered=true";++ cy.task("computeHmac", {+ key: hashKey,+ message: tamperedPayload,+ algorithm,+ }).then((tamperedSignature) => {+ expect(+ tamperedSignature,+ "Tampered payload should produce a different signature"+ ).to.not.equal(computedSignature);++ cy.task(+ "cli_log",+ `Failure scenario verified - tampered payload produces different signature`+ );+ });+});++Cypress.Commands.add("verifyWrongKeySignatureFails", (globalState) => {+ const computedSignature = globalState.get("computedSignature");+ const signingPayload = globalState.get("computedSigningPayload");++ expect(+ computedSignature,+ "computedSignature must exist from prior step - ensure computeAndVerifyRedirectSignature was called first"+ ).to.be.a("string").and.not.be.empty;++ expect(+ signingPayload,+ "computedSigningPayload must exist from prior step - ensure computeAndVerifyRedirectSignature was called first"+ ).to.be.a("string").and.not.be.empty;++ const algorithm = HASH_ALGO;+ const wrongKey = "wrong_key_that_should_not_match";++ cy.task("computeHmac", {+ key: wrongKey,+ message: signingPayload,+ algorithm,+ }).then((wrongKeySignature) => {+ expect(+ wrongKeySignature,+ "Signature computed with wrong key should not match the correct signature"+ ).to.not.equal(computedSignature);++ cy.task(+ "cli_log",+ `Failure scenario verified - wrong-key signature does not match the correct signature`+ );+ });+});++Cypress.Commands.add("captureRedirectReturnUrl", (globalState) => {+ const baseUrl = globalState.get("baseUrl");+ const paymentId = globalState.get("paymentID");+ const merchantId = globalState.get("merchantId");+ const connectorId = getOriginalConnectorName(globalState.get("connectorId"));+ const url = `${baseUrl}/payments/${paymentId}/${merchantId}/redirect/response/${connectorId}`;++ /**+ * Attempt to capture the redirect return URL with polling retry.+ * The payment may not immediately be in redirect-ready state,+ * so we retry up to MAX_RETRIES with DELAY_MS between attempts.+ */+ const MAX_RETRIES = 5;+ const DELAY_MS = 2000;++ function attemptCapture(remainingAttempts) {+ return cy+ .request({+ method: "GET",+ url,+ followRedirect: false,+ failOnStatusCode: false,+ })+ .then((response) => {+ if (response.status === 302 && response.headers.location) {+ globalState.set("redirectReturnUrl", response.headers.location);+ cy.task(+ "cli_log",+ "captureRedirectReturnUrl: captured redirect return URL with signature"+ );+ return;+ }++ if (remainingAttempts > 1) {+ cy.task(+ "cli_log",+ `captureRedirectReturnUrl: got status ${response.status}, retrying in ${DELAY_MS}ms (${MAX_RETRIES - remainingAttempts + 1}/${MAX_RETRIES})`+ );+ return cy+ .wait(DELAY_MS)+ .then(() => attemptCapture(remainingAttempts - 1));+ }++ // Final attempt failed — throw so the test fails loudly+ throw new Error(+ `captureRedirectReturnUrl: expected 302 with Location header, got ${response.status}. ` ++ `Headers: ${JSON.stringify(response.headers)}`+ );+ });+ }++ attemptCapture(MAX_RETRIES);+});+// ============================================// Forex Rates Commands// ============================================diff --git a/cypress-tests/cypress/utils/paymentHelpers.js b/cypress-tests/cypress/utils/paymentHelpers.jsnew file mode 100644index 0000000000..6e9ca58375--- /dev/null+++ b/cypress-tests/cypress/utils/paymentHelpers.js@@ -0,0 +1,62 @@+import getConnectorDetails, * as utils from "../e2e/configs/Payment/Utils";++/**+ * Helper function to setup a 3DS payment flow+ * @param {Object} globalState - globalState object for managing test state and persisting data across test steps+ * @param {Object} options - Configuration options for customizing 3DS payment setup behavior+ * @param {boolean} options.includeRedirection - Controls whether to handle browser redirection after 3DS authentication (default: true). Set to false when testing signature/HMAC verification without full redirect flow.+ * @param {Object} options.fixtures - Test fixtures object containing createPaymentBody and confirmBody for payment setup+ */+export function setup3DSPayment(globalState, options = {}) {+ // Destructure options with defaults: includeRedirection controls redirect handling, fixtures provides test data+ const { includeRedirection = true, fixtures } = options;+ let shouldContinue = true;++ // Fetch PaymentIntent configuration for card payment method from the connector's config+ // This determines the request/response expectations based on the configured connector+ const data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][+ "PaymentIntent"+ ];++ cy.createPaymentIntentTest(+ fixtures.createPaymentBody,+ data,+ "three_ds",+ "automatic",+ globalState+ );++ if (!utils.should_continue_further(data)) {+ shouldContinue = false;+ }++ if (!shouldContinue) {+ cy.task("cli_log", "setup3DSPayment: stopping after createPaymentIntent");+ globalState.set("_setup3DSContinue", false);+ return;+ }++ cy.paymentMethodsCallTest(globalState);++ // Fetch 3DS Auto-Capture configuration for card payment method from the connector's config+ const confirmData = getConnectorDetails(globalState.get("connectorId"))[+ "card_pm"+ ]["3DSAutoCapture"];++ cy.confirmCallTest(fixtures.confirmBody, confirmData, true, globalState);++ if (!utils.should_continue_further(confirmData)) {+ shouldContinue = false;+ }++ if (shouldContinue) {+ cy.captureRedirectReturnUrl(globalState);+ }++ if (includeRedirection && shouldContinue) {+ const expected_redirection = fixtures.confirmBody["return_url"];+ cy.handleRedirection(globalState, expected_redirection);+ }++ globalState.set("_setup3DSContinue", shouldContinue);+}