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
feat(cypress): add MITM proxy record/replay for connector tests (#12852)
venkatakarthikm-makerc0ce9fbf944e
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.ymlindex 1706add02a..a607c0300d 100644--- a/.github/workflows/cypress-tests-runner.yml+++ b/.github/workflows/cypress-tests-runner.yml@@ -27,7 +27,9 @@ env:EXTENDED_PAYMENTS_CONNECTORS_BATCH_1: "bluesnap gigadat loonio nmi"EXTENDED_PAYMENTS_CONNECTORS_BATCH_2: "paypal redsys zift"EXTENDED_PAYOUTS_CONNECTORS: "adyenplatform wise"- MOCK_PAYMENTS_CONNECTORS: "bluesnap gigadat zift loonio cashtocode"+ MOCK_PAYMENTS_CONNECTORS_BATCH_1: "bluesnap gigadat zift loonio cashtocode"+ MOCK_PAYMENTS_CONNECTORS_BATCH_2: "redsys worldpayxml cybersource braintree fiuu"+ MOCK_PAYMENTS_CONNECTORS_BATCH_3: "nmi calida adyen"MOCK_PAYOUTS_CONNECTORS: "adyenplatform wise"RUST_BACKTRACE: shortRUSTUP_MAX_RETRIES: 10@@ -743,13 +745,31 @@ jobs:"server_logs_artifact": "mock-server-logs-payouts"},{- "name": "mock-payments",- "payments_connectors": "'"${MOCK_PAYMENTS_CONNECTORS}"'",+ "name": "mock-payments-batch-1",+ "payments_connectors": "'"${MOCK_PAYMENTS_CONNECTORS_BATCH_1}"'","payouts_connectors": "","platform_connectors": "","parallel": 5,- "report_artifact_name": "cypress-mock-test-results-payments",- "server_logs_artifact": "mock-server-logs-payments"+ "report_artifact_name": "cypress-mock-test-results-payments-batch-1",+ "server_logs_artifact": "mock-server-logs-payments-batch-1"+ },+ {+ "name": "mock-payments-batch-2",+ "payments_connectors": "'"${MOCK_PAYMENTS_CONNECTORS_BATCH_2}"'",+ "payouts_connectors": "",+ "platform_connectors": "",+ "parallel": 5,+ "report_artifact_name": "cypress-mock-test-results-payments-batch-2",+ "server_logs_artifact": "mock-server-logs-payments-batch-2"+ },+ {+ "name": "mock-payments-batch-3",+ "payments_connectors": "'"${MOCK_PAYMENTS_CONNECTORS_BATCH_3}"'",+ "payouts_connectors": "",+ "platform_connectors": "",+ "parallel": 4,+ "report_artifact_name": "cypress-mock-test-results-payments-batch-3",+ "server_logs_artifact": "mock-server-logs-payments-batch-3"}]}'@@ -1041,6 +1061,7 @@ jobs:ROUTER__TRACE_HEADER__ID_REUSE_STRATEGY: "use_incoming"ROUTER__SERVER__WORKERS: 4SERVER_LOG_PATH: ${{ github.workspace }}/server-logs.txt+ RUST_MIN_STACK: 134217728shell: bashrun: |MITM_CERT=$(sed 's/$/\\r\\n/' "$HOME/.mitmproxy/mitmproxy-ca-cert.pem" | tr -d '\n')@@ -1098,6 +1119,7 @@ jobs:# Notifies the MITM proxy of each test start/end so test names appear# in the replay log alongside cassette hits/misses (logging only).CYPRESS_PROXY_ADMIN_URL: "http://127.0.0.1:8001"+ CYPRESS_CAPTURE_DIR: "${{ github.workspace }}/cypress-tests/mitm-proxy/captures"shell: bash -leuo pipefail {0}run: |scripts/execute_cypress.sh --parallel ${{ matrix.batch.parallel }}diff --git a/cypress-tests/.gitignore b/cypress-tests/.gitignoreindex cd5dbe44f4..dbcaec5b6c 100644--- a/cypress-tests/.gitignore+++ b/cypress-tests/.gitignore@@ -10,4 +10,4 @@ creds.jsonrun_all.sh# Cypress Dashboard build-**/dist\ No newline at end of file+**/distdiff --git a/cypress-tests/cypress.config.js b/cypress-tests/cypress.config.jsindex fcde576b7a..94d71fe437 100644--- a/cypress-tests/cypress.config.js+++ b/cypress-tests/cypress.config.js@@ -27,6 +27,14 @@ export default defineConfig({getGlobalState: () => {return globalState || {};},+ readFileOrNull: (filePath) => {+ if (!fs.existsSync(filePath)) return null;+ try {+ return JSON.parse(fs.readFileSync(filePath, "utf8"));+ } catch {+ return null;+ }+ },cli_log: (message) => {// eslint-disable-next-line no-consoleconsole.log("Logging console message from task");diff --git a/cypress-tests/cypress/e2e/configs/Payment/Calida.js b/cypress-tests/cypress/e2e/configs/Payment/Calida.jsindex 47f04fe01f..c543dd3d60 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Calida.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Calida.js@@ -11,6 +11,12 @@ const bluecodeBilling = {export const connectorDetails = {wallet_pm: {Bluecode: {+ Configs: {+ DELAY: {+ STATUS: true,+ TIMEOUT: 5000,+ },+ },Request: {payment_method: "wallet",payment_method_type: "bluecode",diff --git a/cypress-tests/cypress/e2e/configs/Payment/Utils.js b/cypress-tests/cypress/e2e/configs/Payment/Utils.jsindex 6b2cfdc956..b7d55d9ced 100644--- a/cypress-tests/cypress/e2e/configs/Payment/Utils.js+++ b/cypress-tests/cypress/e2e/configs/Payment/Utils.js@@ -490,6 +490,7 @@ export const CONNECTOR_LISTS = {"billwerk","bluesnap","braintree",+ "calida","cashtocode","facilitapay","fiserv",@@ -500,6 +501,7 @@ export const CONNECTOR_LISTS = {"jpmorgan","loonio","nexinets",+ "nmi","noon","novalnet","payload",@@ -514,6 +516,7 @@ export const CONNECTOR_LISTS = {],MANDATE_ID_TEST: ["airwallex",+ "calida","payload","gigadat","loonio",diff --git a/cypress-tests/cypress/e2e/spec/Payment/19-Wallet.cy.js b/cypress-tests/cypress/e2e/spec/Payment/19-Wallet.cy.jsindex 21715e2381..ab019c7868 100644--- a/cypress-tests/cypress/e2e/spec/Payment/19-Wallet.cy.js+++ b/cypress-tests/cypress/e2e/spec/Payment/19-Wallet.cy.js@@ -54,7 +54,7 @@ describe("Wallet tests", () => {cy.createPaymentIntentTest(fixtures.createPaymentBody,data,- "three_ds",+ "no_three_ds","automatic",globalState);diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.jsindex a8aa2d28bf..a7a93cd23d 100644--- a/cypress-tests/cypress/support/commands.js+++ b/cypress-tests/cypress/support/commands.js@@ -36,12 +36,16 @@ import { execConfig, validateConfig } from "../utils/featureFlags";import * as RequestBodyUtils from "../utils/RequestBodyUtils";import { isoTimeTomorrow, validateEnv } from "../utils/RequestBodyUtils.js";import { handleRedirection, MICRODEPOSIT_CONFIG } from "./redirectionHandler";--// In MITM replay mode (MOCK_SERVER=true) there is no live browser redirection-// to drive. Cypress.env may return a boolean or a string, hence String().-function isMockServer() {- return String(Cypress.env("MOCK_SERVER")) === "true";-}+import {+ isMockServer,+ isRecordMode,+ isReplayMode,+ mockRecord3ds,+ mockRecordBankRedirect,+ mockReplay3ds,+ mockReplayBankRedirect,+ resetMitmRedirectSeq,+} from "./mitmProxy";// Returns true (after logging a consistent skip line) when a redirection// command should bail out early because we're in replay mode.@@ -5230,9 +5234,9 @@ Cypress.Commands.add("handleRedirection",(globalState, expectedRedirection) => {const connectorId = globalState.get("connectorId");- // Cassettes recorded from a non-3DS scenario won't carry a- // next_action URL; fall back to example.com so replay can still- // burn the step-counter slot and reach later assertions.+ // Cassettes recorded from a non-3DS scenario won't carry a next_action+ // URL; fall back to example.com so replay can still burn the step-counter+ // slot and reach later assertions.let nextActionUrl = globalState.get("nextActionUrl");if (!nextActionUrl) {cy.task(@@ -5242,29 +5246,27 @@ Cypress.Commands.add(nextActionUrl = "https://example.com";}- if (isMockServer()) {- // In MITM replay mode the ThreeDS browser flow is skipped. Consume one- // cy.request slot so the Cypress step counter stays aligned with how the- // cassettes were recorded (threeDsRedirection() always issues one request- // before starting browser navigation). The force_sync Retrieve that- // follows will call Stripe PSync, receive "requires_capture" from the- // cassette, and HS transitions the payment state automatically.- if (Cypress.env("PROXY_ADMIN_URL")) {- cy.request({- url: nextActionUrl,- failOnStatusCode: false,- followRedirect: false,- });- }+ if (isRecordMode()) {+ mockRecord3ds(+ globalState,+ nextActionUrl,+ expectedRedirection,+ handleRedirection+ );return;}- const expectedUrl = new URL(expectedRedirection);- const redirectionUrl = new URL(nextActionUrl);+ if (isReplayMode()) {+ mockReplay3ds(globalState, connectorId, nextActionUrl);+ return;+ }handleRedirection("three_ds",- { redirectionUrl, expectedUrl },+ {+ redirectionUrl: new URL(nextActionUrl),+ expectedUrl: new URL(expectedRedirection),+ },connectorId,globalState.get("paymentMethodType"));@@ -5277,6 +5279,28 @@ Cypress.Commands.add(const connectorId = globalState.get("connectorId");const nextActionUrl = globalState.get("nextActionUrl");+ // explicitly restricting `sofort` payment method by adyen from running as it stops other tests from running+ // trying to handle that specific case results in stripe 3ds tests to fail+ if (connectorId === "adyen" && paymentMethodType === "sofort") {+ return;+ }++ if (isRecordMode()) {+ mockRecordBankRedirect(+ globalState,+ nextActionUrl,+ expectedRedirection,+ paymentMethodType,+ handleRedirection+ );+ return;+ }++ if (isReplayMode()) {+ mockReplayBankRedirect(globalState, connectorId);+ return;+ }+if (skipRedirectionInMockServer("handleBankRedirectRedirection")) {return;}@@ -5284,21 +5308,17 @@ Cypress.Commands.add(const expectedUrl = new URL(expectedRedirection);const redirectionUrl = new URL(nextActionUrl);- // explicitly restricting `sofort` payment method by adyen from running as it stops other tests from running- // trying to handle that specific case results in stripe 3ds tests to fail- if (!(connectorId == "adyen" && paymentMethodType == "sofort")) {- // Wrap in cy.then() so that commands enqueued by handleRedirection- // (especially cy.origin() calls for PayJustNow) are chained inline- // and complete before subsequent test steps (Retrieve Payment, Refund).- cy.then(() => {- handleRedirection(- "bank_redirect",- { redirectionUrl, expectedUrl },- connectorId,- paymentMethodType- );- });- }+ // Wrap in cy.then() so that commands enqueued by handleRedirection+ // (especially cy.origin() calls for PayJustNow) are chained inline+ // and complete before subsequent test steps (Retrieve Payment, Refund).+ cy.then(() => {+ handleRedirection(+ "bank_redirect",+ { redirectionUrl, expectedUrl },+ connectorId,+ paymentMethodType+ );+ });});@@ -10717,3 +10737,7 @@ Cypress.Commands.add("retrieveNonExistentPayoutTest", (globalState) => {expect(response.status).to.equal(404);});});++Cypress.Commands.add("resetRedirectReadCount", (testIdHash) => {+ resetMitmRedirectSeq(testIdHash);+});diff --git a/cypress-tests/cypress/support/e2e.js b/cypress-tests/cypress/support/e2e.jsindex 23d79e7eeb..71c92d77d3 100644--- a/cypress-tests/cypress/support/e2e.js+++ b/cypress-tests/cypress/support/e2e.js@@ -24,6 +24,7 @@ Cypress.on("uncaught:exception", (err, runnable) => {// (the proxy's cassette match key on replay).const IS_PROXY_ENABLED = String(Cypress.env("IS_PROXY_ENABLED")) === "true";const PROXY_ADMIN_URL = Cypress.env("PROXY_ADMIN_URL");+const REDIRECT_PROXY_ADMIN_URL = Cypress.env("REDIRECT_PROXY_ADMIN_URL");const PROXY_ADMIN_TIMEOUT_MS = 2000;const REQUEST_ID_HEADER = "X-Request-ID";const STEP_COUNTER_DIGITS = 3;@@ -81,7 +82,11 @@ function normalizeRequestArgs(args) {// Proxy-admin calls are control traffic and must not consume a step slot.function isProxyAdminUrl(url) {- return Boolean(url) && url.startsWith(PROXY_ADMIN_URL);+ if (!url) return false;+ if (PROXY_ADMIN_URL && url.startsWith(PROXY_ADMIN_URL)) return true;+ if (REDIRECT_PROXY_ADMIN_URL && url.startsWith(REDIRECT_PROXY_ADMIN_URL))+ return true;+ return false;}function buildRequestId() {@@ -115,6 +120,9 @@ function notifyProxyTestEnded() {}if (IS_PROXY_ENABLED) {+ Cypress._getStepCounter = () => stepCounter;+ Cypress._buildRequestId = buildRequestId;+beforeEach(() => {const { titlePath } = Cypress.currentTest;const title = titlePath.join(" > ");@@ -123,10 +131,22 @@ if (IS_PROXY_ENABLED) {testIdHash = computeTestIdHash(connector, spec, title);stepCounter = 0;+ Cypress.env("currentTestIdHash", testIdHash);+ cy.resetRedirectReadCount(testIdHash);if (PROXY_ADMIN_URL) {notifyProxyTestStarted(titlePath, spec, connector);}++ if (REDIRECT_PROXY_ADMIN_URL) {+ cy.request({+ method: "POST",+ url: `${REDIRECT_PROXY_ADMIN_URL}/test/start`,+ body: { testIdHash },+ failOnStatusCode: false,+ timeout: PROXY_ADMIN_TIMEOUT_MS,+ });+ }});afterEach(() => {diff --git a/cypress-tests/cypress/support/mitmProxy.js b/cypress-tests/cypress/support/mitmProxy.jsnew file mode 100644index 0000000000..448be3c94a--- /dev/null+++ b/cypress-tests/cypress/support/mitmProxy.js@@ -0,0 +1,268 @@+/**+ * MITM proxy helpers for record/replay of 3DS and bank-redirect flows.+ *+ * Record mode – REDIRECT_PROXY_ADMIN_URL is set, MOCK_SERVER is false.+ * Cypress reserves a RID with the redirect proxy before the+ * browser navigates to the ACS, so the proxy can inject it on+ * the return leg and tie the outbound connector call to the+ * right cassette.+ *+ * Replay mode – IS_PROXY_ENABLED=true, MOCK_SERVER=true.+ * The browser flow is skipped; Cypress reads the saved redirect+ * body from CAPTURE_DIR and POST/GETs it directly to the router.+ */++// ── Connectors whose redirect return is a GET to a known path ────────────────++const JS_IFRAME_CONNECTORS = {+ stripe: {+ path: "redirect/response",+ params: (gs) => ({+ payment_intent: gs.get("connectorTransactionID"),+ redirect_status: "succeeded",+ }),+ },+ stripeconnect: {+ path: "redirect/response",+ params: (gs) => ({+ payment_intent: gs.get("connectorTransactionID"),+ redirect_status: "succeeded",+ }),+ },+};++// ── Module-level sequence counter (reset per test via resetMitmRedirectSeq) ──++const _redirectReadCount = {};++// ── Mode checks ──────────────────────────────────────────────────────────────++export function isMockServer() {+ return String(Cypress.env("MOCK_SERVER")) === "true";+}++export function isRecordMode() {+ return !!Cypress.env("REDIRECT_PROXY_ADMIN_URL") && !isMockServer();+}++export function isReplayMode() {+ return String(Cypress.env("IS_PROXY_ENABLED")) === "true" && isMockServer();+}++// ── Sequence counter ─────────────────────────────────────────────────────────++export function resetMitmRedirectSeq(testIdHash) {+ delete _redirectReadCount[testIdHash];+}++function nextRedirectSeq(testIdHash) {+ _redirectReadCount[testIdHash] = (_redirectReadCount[testIdHash] || 0) + 1;+ return String(_redirectReadCount[testIdHash]).padStart(3, "0");+}++function getRedirectBodyFile(connectorId, testIdHash, seq) {+ const captureDir = Cypress.env("CAPTURE_DIR");+ return `${captureDir}/${connectorId}/Payment/redirect-bodies/${testIdHash}-${seq}-redirect-body.json`;+}++// ── Record helpers ───────────────────────────────────────────────────────────++function reserveRedirectRid(testIdHash, paymentId, stepOffset) {+ const adminUrl = Cypress.env("REDIRECT_PROXY_ADMIN_URL");+ const currentStep = Cypress._getStepCounter ? Cypress._getStepCounter() : 0;+ const rid = `${testIdHash}-${String(currentStep + stepOffset).padStart(3, "0")}`;+ cy.request({+ method: "POST",+ url: `${adminUrl}/reserve`,+ body: { rid, testIdHash, paymentId },+ failOnStatusCode: false,+ timeout: 2000,+ });+}++export function mockRecord3ds(+ globalState,+ nextActionUrl,+ expectedRedirection,+ handleRedirectionFn+) {+ const connectorId = globalState.get("connectorId");+ const testIdHash = Cypress.env("currentTestIdHash") || "unknown";+ const paymentId = globalState.get("paymentID");++ reserveRedirectRid(testIdHash, paymentId, 2);++ handleRedirectionFn(+ "three_ds",+ {+ redirectionUrl: new URL(nextActionUrl),+ expectedUrl: new URL(expectedRedirection),+ },+ connectorId,+ globalState.get("paymentMethodType")+ );+ cy.then(() => {+ if (Cypress._buildRequestId) Cypress._buildRequestId();+ });+}++export function mockRecordBankRedirect(+ globalState,+ nextActionUrl,+ expectedRedirection,+ paymentMethodType,+ handleRedirectionFn+) {+ const connectorId = globalState.get("connectorId");+ const testIdHash = Cypress.env("currentTestIdHash") || "unknown";+ const paymentId = globalState.get("paymentID");++ reserveRedirectRid(testIdHash, paymentId, 1);++ handleRedirectionFn(+ "bank_redirect",+ {+ redirectionUrl: new URL(nextActionUrl),+ expectedUrl: new URL(expectedRedirection),+ },+ connectorId,+ paymentMethodType+ );+ cy.then(() => {+ if (Cypress._buildRequestId) Cypress._buildRequestId();+ });+}++// ── Replay helpers ───────────────────────────────────────────────────────────++function replayRedirectBody(saved, paymentId, merchantId, notificationUrl) {+ const hyperswitchUrl =+ Cypress.env("HYPERSWITCH_URL") || "http://localhost:8080";+ if (saved && saved.__redirect_method === "GET") {+ const qs = new URLSearchParams(saved.__query || {}).toString();+ const base = saved.__redirect_segment+ ? `${hyperswitchUrl}/payments/${paymentId}/${merchantId}/${saved.__redirect_segment}`+ : notificationUrl;+ cy.request({+ method: "GET",+ url: qs ? `${base}?${qs}` : base,+ failOnStatusCode: false,+ followRedirect: false,+ });+ } else if (saved) {+ const postBody =+ saved.__redirect_method === "POST" && saved.__body ? saved.__body : saved;+ const postUrl = saved.__redirect_segment+ ? `${hyperswitchUrl}/payments/${paymentId}/${merchantId}/${saved.__redirect_segment}`+ : notificationUrl;+ cy.request({+ method: "POST",+ url: postUrl,+ form: true,+ body: postBody,+ failOnStatusCode: false,+ followRedirect: false,+ });+ } else {+ cy.then(() => {+ if (Cypress._buildRequestId) Cypress._buildRequestId();+ });+ }+}++function replayJsConnectorRedirect(+ jsConnector,+ saved,+ paymentId,+ merchantId,+ globalState+) {+ const hyperswitchUrl =+ Cypress.env("HYPERSWITCH_URL") || "http://localhost:8080";+ if (saved && saved.__redirect_method === "GET" && saved.__redirect_segment) {+ const url = `${hyperswitchUrl}/payments/${paymentId}/${merchantId}/${saved.__redirect_segment}`;+ const qs = new URLSearchParams(saved.__query || {}).toString();+ cy.request({+ method: "GET",+ url: qs ? `${url}?${qs}` : url,+ failOnStatusCode: false,+ followRedirect: false,+ });+ } else {+ const returnUrl = `${hyperswitchUrl}/payments/${paymentId}/${merchantId}/${jsConnector.path}/${globalState.get("connectorId")}`;+ const params = jsConnector.params(globalState);+ const hasValues = Object.values(params).every(+ (v) => v !== undefined && v !== null+ );+ if (hasValues) {+ const qs = new URLSearchParams(params).toString();+ cy.request({+ method: "GET",+ url: `${returnUrl}?${qs}`,+ failOnStatusCode: false,+ followRedirect: false,+ });+ } else {+ cy.then(() => {+ if (Cypress._buildRequestId) Cypress._buildRequestId();+ });+ }+ }+}++function replayRedirect(+ connectorId,+ globalState,+ redirectBodyFile,+ notificationUrl+) {+ const paymentId = globalState.get("paymentID");+ const merchantId = globalState.get("merchantId");+ const jsConnector = JS_IFRAME_CONNECTORS[connectorId];++ if (jsConnector) {+ cy.task("readFileOrNull", redirectBodyFile).then((saved) => {+ replayJsConnectorRedirect(+ jsConnector,+ saved,+ paymentId,+ merchantId,+ globalState+ );+ });+ return;+ }++ cy.task("readFileOrNull", redirectBodyFile).then((saved) => {+ replayRedirectBody(saved, paymentId, merchantId, notificationUrl);+ });+}++export function mockReplay3ds(globalState, connectorId, nextActionUrl) {+ const baseUrl = globalState.get("baseUrl");+ const paymentId = globalState.get("paymentID");+ const merchantId = globalState.get("merchantId");+ const testIdHash = Cypress.env("currentTestIdHash") || "unknown";+ const seq = nextRedirectSeq(testIdHash);+ const redirectBodyFile = getRedirectBodyFile(connectorId, testIdHash, seq);+ const notificationUrl = `${baseUrl}/payments/${paymentId}/${merchantId}/redirect/complete/${connectorId}`;++ cy.request({+ url: nextActionUrl,+ failOnStatusCode: false,+ followRedirect: false,+ });+ replayRedirect(connectorId, globalState, redirectBodyFile, notificationUrl);+}++export function mockReplayBankRedirect(globalState, connectorId) {+ const baseUrl = globalState.get("baseUrl");+ const paymentId = globalState.get("paymentID");+ const merchantId = globalState.get("merchantId");+ const testIdHash = Cypress.env("currentTestIdHash") || "unknown";+ const seq = nextRedirectSeq(testIdHash);+ const redirectBodyFile = getRedirectBodyFile(connectorId, testIdHash, seq);+ const notificationUrl = `${baseUrl}/payments/${paymentId}/${merchantId}/redirect/complete/${connectorId}`;++ replayRedirect(connectorId, globalState, redirectBodyFile, notificationUrl);+}diff --git a/cypress-tests/mitm-proxy/redirect_proxy.py b/cypress-tests/mitm-proxy/redirect_proxy.pynew file mode 100644index 0000000000..8e380a6507--- /dev/null+++ b/cypress-tests/mitm-proxy/redirect_proxy.py@@ -0,0 +1,301 @@+"""+Redirect proxy — sits in front of Hyperswitch on port 9001.+Injects X-Request-ID on redirect/complete and redirect/response calls so the+MITM proxy can attribute the outbound connector call to the right cassette.+Saves the redirect body for replay.++Admin (port 9002): POST /test/start, POST /reserve, GET /status+Run: python redirect_proxy.py+"""++import http.client+import json+import os+import re+import threading+import urllib.parse+from http.server import BaseHTTPRequestHandler, HTTPServer++SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))+CAPTURE_DIR = os.environ.get(+ "CAPTURE_DIR",+ os.path.normpath(os.path.join(SCRIPT_DIR, "captures")),+)+LISTEN_PORT = int(os.environ.get("REDIRECT_PROXY_PORT", "9001"))+ADMIN_PORT = int(os.environ.get("REDIRECT_PROXY_ADMIN_PORT", "9002"))+UPSTREAM_HOST = os.environ.get("REDIRECT_PROXY_UPSTREAM_HOST", "localhost")+UPSTREAM_PORT = int(os.environ.get("REDIRECT_PROXY_UPSTREAM_PORT", "8080"))++_HOP_BY_HOP = frozenset(("host", "content-length", "transfer-encoding", "connection"))++_lock = threading.Lock()+_reserved: dict[str, dict] = {}+_redirect_count: dict[str, int] = {}+++# ── Path helpers ──────────────────────────────────────────────────────────────++def _is_redirect_complete(path: str) -> bool:+ return "/redirect/complete/" in path or "/redirect/response/" in path+++def _extract_payment_id(path: str) -> str:+ parts = path.split("/")+ return parts[2] if len(parts) > 2 else ""+++def _extract_redirect_segment(path: str) -> str | None:+ parts = path.split("/")+ try:+ idx = parts.index("redirect")+ return "/".join(parts[idx:])+ except ValueError:+ return None+++# ── Body parsing ──────────────────────────────────────────────────────────────++def _parse_post_body(body: bytes, content_type: str) -> dict | str:+ ct = content_type.lower()+ try:+ if "json" in ct:+ return json.loads(body)+ if "form" in ct or "x-www-form-urlencoded" in ct:+ return dict(urllib.parse.parse_qsl(body.decode("utf-8")))+ return body.decode("utf-8", errors="replace")+ except Exception:+ return body.decode("utf-8", errors="replace")+++def _build_redirect_data(+ method: str,+ path_only: str,+ query_string: str,+ body: bytes,+ content_type: str,+) -> dict | None:+ redirect_segment = _extract_redirect_segment(path_only)++ if method == "GET":+ query_params = dict(urllib.parse.parse_qsl(query_string)) if query_string else {}+ data: dict = {"__redirect_method": "GET", "__query": query_params}+ else:+ if not body:+ return None+ data = {"__redirect_method": "POST", "__body": _parse_post_body(body, content_type)}++ if redirect_segment:+ data["__redirect_segment"] = redirect_segment+ return data+++# ── Persistence ───────────────────────────────────────────────────────────────++def _write_json(path: str, data: dict) -> None:+ with open(path, "w") as f:+ json.dump(data, f, indent=2)+++def _write_to_captures(data: dict, filename: str) -> None:+ redirect_segment = data.get("__redirect_segment")+ if not redirect_segment:+ return++ raw_connector = redirect_segment.split("/")[-1]+ connector = re.sub(r"[^a-zA-Z0-9\-]", "", raw_connector)+ if not connector:+ return++ captures_body_dir = os.path.join(CAPTURE_DIR, connector, "Payment", "redirect-bodies")+ real_dir = os.path.realpath(captures_body_dir)+ real_base = os.path.realpath(CAPTURE_DIR)++ if not real_dir.startswith(real_base + os.sep):+ print(f"[redirect-proxy] WARNING: resolved path {real_dir!r} escapes CAPTURE_DIR — skipping")+ return++ os.makedirs(real_dir, exist_ok=True)+ captures_path = os.path.realpath(os.path.join(real_dir, os.path.basename(filename)))++ if not captures_path.startswith(real_dir + os.sep):+ print(f"[redirect-proxy] WARNING: resolved file path {captures_path!r} escapes target dir — skipping")+ return++ _write_json(captures_path, data)+ print(f"[redirect-proxy] body also saved → {captures_path}")+++def _save_redirect(+ test_id_hash: str,+ method: str,+ path_only: str,+ query_string: str,+ body: bytes,+ content_type: str,+) -> None:+ data = _build_redirect_data(method, path_only, query_string, body, content_type)+ if data is None:+ return++ with _lock:+ _redirect_count[test_id_hash] = _redirect_count.get(test_id_hash, 0) + 1+ seq = str(_redirect_count[test_id_hash]).zfill(3)++ filename = f"{test_id_hash}-{seq}-redirect-body.json"++ _write_to_captures(data, filename)+++# ── Proxy handler ─────────────────────────────────────────────────────────────++class ProxyHandler(BaseHTTPRequestHandler):++ def _read_body(self) -> bytes:+ length = int(self.headers.get("Content-Length", 0))+ return self.rfile.read(length) if length else b""++ def _forward_headers(self) -> dict[str, str]:+ return {k: v for k, v in self.headers.items() if k.lower() not in _HOP_BY_HOP}++ def _inject_rid(self, path_only: str, body: bytes, headers: dict) -> None:+ payment_id = _extract_payment_id(path_only)+ with _lock:+ entry = _reserved.pop(payment_id, None)++ if entry:+ headers["X-Request-ID"] = entry["rid"]+ print(f"[redirect-proxy] injected RID {entry['rid']} for paymentId={payment_id}")+ query_string = self.path.split("?", 1)[1] if "?" in self.path else ""+ _save_redirect(+ entry["testIdHash"],+ self.command,+ path_only,+ query_string,+ body,+ self.headers.get("Content-Type", ""),+ )+ else:+ print(f"[redirect-proxy] WARNING: no reserved RID for paymentId={payment_id} path={self.path}")++ def _call_upstream(self, headers: dict, body: bytes):+ conn = http.client.HTTPConnection(UPSTREAM_HOST, UPSTREAM_PORT, timeout=30)+ try:+ conn.request(self.command, self.path, body=body or None, headers=headers)+ resp = conn.getresponse()+ return resp.status, list(resp.getheaders()), resp.read()+ finally:+ try:+ conn.close()+ except Exception:+ pass++ def _forward(self):+ body = self._read_body()+ path_only = self.path.split("?", 1)[0]+ headers = self._forward_headers()++ if _is_redirect_complete(path_only):+ self._inject_rid(path_only, body, headers)++ try:+ status, resp_headers, resp_body = self._call_upstream(headers, body)+ except Exception as exc:+ self.send_error(502, f"Upstream error: {exc}")+ return++ self.send_response(status)+ for k, v in resp_headers:+ if k.lower() not in ("transfer-encoding", "connection"):+ self.send_header(k, v)+ self.end_headers()+ self.wfile.write(resp_body)++ do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_HEAD = _forward++ def log_message(self, *_):+ pass+++# ── Admin handler ─────────────────────────────────────────────────────────────++class AdminHandler(BaseHTTPRequestHandler):++ def _json(self, code: int, payload: dict) -> None:+ body = json.dumps(payload).encode()+ self.send_response(code)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def _read_json_body(self) -> dict:+ length = int(self.headers.get("Content-Length", 0))+ try:+ return json.loads(self.rfile.read(length) or b"{}")+ except json.JSONDecodeError:+ return {}++ def _handle_test_start(self, data: dict) -> None:+ test_id_hash = (data.get("testIdHash") or "").strip()+ with _lock:+ _redirect_count.pop(test_id_hash, None)+ print(f"[redirect-proxy] test/start hash={test_id_hash or '(none)'}")+ self._json(200, {"ok": True})++ def _handle_reserve(self, data: dict) -> None:+ rid = (data.get("rid") or "").strip()+ test_id_hash = (data.get("testIdHash") or "").strip()+ payment_id = (data.get("paymentId") or "").strip()+ if rid and test_id_hash and payment_id:+ with _lock:+ _reserved[payment_id] = {"rid": rid, "testIdHash": test_id_hash}+ print(f"[redirect-proxy] reserved {rid} for paymentId={payment_id} hash={test_id_hash}")+ self._json(200, {"ok": True})+ else:+ self._json(400, {"ok": False, "reason": "missing rid, testIdHash, or paymentId"})++ def do_POST(self):+ data = self._read_json_body()+ handlers = {+ "/test/start": self._handle_test_start,+ "/reserve": self._handle_reserve,+ }+ handler = handlers.get(self.path)+ if handler:+ handler(data)+ else:+ self._json(404, {"error": "unknown path"})++ def do_GET(self):+ if self.path in ("/status", "/"):+ with _lock:+ self._json(200, {+ "reserved": dict(_reserved),+ "capture_dir": CAPTURE_DIR,+ "upstream": f"{UPSTREAM_HOST}:{UPSTREAM_PORT}",+ })+ else:+ self._json(404, {"error": "unknown path"})++ def log_message(self, *_):+ pass+++# ── Entry point ───────────────────────────────────────────────────────────────++def _start_admin() -> None:+ server = HTTPServer(("127.0.0.1", ADMIN_PORT), AdminHandler)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ print(f"[redirect-proxy] admin http://127.0.0.1:{ADMIN_PORT}")+++def main() -> None:+ _start_admin()+ proxy = HTTPServer(("0.0.0.0", LISTEN_PORT), ProxyHandler)+ print(f"[redirect-proxy] proxy http://0.0.0.0:{LISTEN_PORT} → http://{UPSTREAM_HOST}:{UPSTREAM_PORT}")+ print(f"[redirect-proxy] bodies {CAPTURE_DIR}")+ proxy.serve_forever()+++if __name__ == "__main__":+ main()diff --git a/cypress-tests/mitm-proxy/start_record.sh b/cypress-tests/mitm-proxy/start_record.shindex 6486aadd7d..ff11b2ed31 100755--- a/cypress-tests/mitm-proxy/start_record.sh+++ b/cypress-tests/mitm-proxy/start_record.sh@@ -1,17 +1,19 @@#!/usr/bin/env bash-# Start mitmproxy in recording mode.+# Start mitmproxy in recording mode + redirect proxy (background).## Usage:-# ./start.sh # default port 8888-# PROXY_PORT=9090 ./start.sh+# ./start_record.sh # default port 8888+# PROXY_PORT=9090 ./start_record.shset -euo pipefailPROXY_PORT="${PROXY_PORT:-8888}"+REDIRECT_PROXY_PORT="${REDIRECT_PROXY_PORT:-9001}"+REDIRECT_PROXY_ADMIN_PORT="${REDIRECT_PROXY_ADMIN_PORT:-9002}"SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"# ── Verify required tooling is installed ──────────────────────────────────-for _tool in uv mitmdump; do+for _tool in uv mitmdump python3; doif ! command -v "${_tool}" >/dev/null 2>&1; thenecho "ERROR: required tool '${_tool}' not found on PATH." >&2echo " Install uv (https://docs.astral.sh/uv/getting-started/installation/) and" >&2@@ -36,6 +38,26 @@ fi# apply_mitm_certificate() expects (it does replace("\\r\\n", "\n") to decode)MITM_CERT=$(sed 's/$/\\r\\n/' "${MITM_CERT_PATH}" | tr -d '\n')+# ── Start redirect proxy in background ────────────────────────────────────+echo "==> Starting redirect proxy on :${REDIRECT_PROXY_PORT} (admin :${REDIRECT_PROXY_ADMIN_PORT}) ..."+REDIRECT_PROXY_PORT="${REDIRECT_PROXY_PORT}" \+REDIRECT_PROXY_ADMIN_PORT="${REDIRECT_PROXY_ADMIN_PORT}" \+ uv run --with-requirements "${SCRIPT_DIR}/requirements.txt" \+ python3 "${SCRIPT_DIR}/redirect_proxy.py" \+ > /tmp/redirect_proxy.log 2>&1 &+REDIRECT_PROXY_PID=$!++# Give it a moment to bind+sleep 1+if ! kill -0 "${REDIRECT_PROXY_PID}" 2>/dev/null; then+ echo "ERROR: redirect proxy failed to start. Check /tmp/redirect_proxy.log" >&2+ exit 1+fi+echo " Redirect proxy running (PID=${REDIRECT_PROXY_PID}), log: /tmp/redirect_proxy.log"++# Kill redirect proxy when this script exits (Ctrl+C or error)+trap 'echo ""; echo "==> Stopping redirect proxy (PID=${REDIRECT_PROXY_PID})..."; kill "${REDIRECT_PROXY_PID}" 2>/dev/null || true' EXIT+# ── Print env vars BEFORE blocking on mitmproxy ───────────────────────────echo ""echo "Copy these exports into the Hyperswitch terminal, then start the router:"@@ -44,15 +66,19 @@ echo "export ROUTER__PROXY__HTTPS_URL=\"http://127.0.0.1:${PROXY_PORT}\""echo "export ROUTER__PROXY__HTTP_URL=\"http://127.0.0.1:${PROXY_PORT}\""echo "export ROUTER__PROXY__MITM_CA_CERTIFICATE=\"${MITM_CERT}\""echo "export ROUTER__TRACE_HEADER__ID_REUSE_STRATEGY=\"use_incoming\""+echo "export ROUTER__MULTITENANCY__TENANTS__PUBLIC__BASE_URL=\"http://localhost:${REDIRECT_PROXY_PORT}\""+echo "export RUST_MIN_STACK=134217728"echo "cargo run --bin router"echo "──────────────────────────────────────────────────────────────────────"echo ""-echo "==> Starting mitmproxy on :${PROXY_PORT} (Ctrl+C to stop)"+echo "==> Starting mitmproxy on :${PROXY_PORT} (Ctrl+C to stop both proxies)"echo " Captures -> ${SCRIPT_DIR}/captures/{connector}/{spec}/{context}/.../NNN.json"echo " Admin API -> http://127.0.0.1:8001"echo ""-echo "Set this in the Cypress terminal so cassettes are organised by spec/test:"+echo "Set these in the Cypress terminal:"echo " export CYPRESS_PROXY_ADMIN_URL=http://127.0.0.1:8001"+echo " export CYPRESS_REDIRECT_PROXY_ADMIN_URL=http://127.0.0.1:${REDIRECT_PROXY_ADMIN_PORT}"+echo " export CYPRESS_IS_PROXY_ENABLED=true"echo ""# ── Run mitmproxy in the foreground so errors are visible ─────────────────diff --git a/cypress-tests/mitm-proxy/start_replay.sh b/cypress-tests/mitm-proxy/start_replay.shindex 9e6b72310a..ce2b7c376b 100755--- a/cypress-tests/mitm-proxy/start_replay.sh+++ b/cypress-tests/mitm-proxy/start_replay.sh@@ -81,8 +81,11 @@ if [[ -t 1 ]]; thenecho " LIVE = request arrived with no x-request-id"echo " BLOCK = strict-mode synthetic 599 (only in --strict)"echo ""- echo "Optional, for log breadcrumbs in the Cypress terminal:"+ echo "Set these in the Cypress terminal:"echo " export CYPRESS_PROXY_ADMIN_URL=http://127.0.0.1:${ADMIN_PORT:-8001}"+ echo " export CYPRESS_IS_PROXY_ENABLED=true"+ echo " export CYPRESS_MOCK_SERVER=true"+ echo " (REDIRECT_PROXY_ADMIN_URL not needed for replay — cy.request goes direct)"echo ""fi@@ -95,9 +98,19 @@ fi# a permissive live-MISS still connects just-in-time.# upstream_cert=false: generate the client-facing cert from the SNI instead# of fetching the real one, so replay never touches the network for certs.-exec uv run --with-requirements "${SCRIPT_DIR}/requirements.txt" \- mitmdump \- -s "${SCRIPT_DIR}/mitm_replay.py" \- --listen-port "${PROXY_PORT}" \- --set connection_strategy=lazy \- --set upstream_cert=false+# If mitmdump is already on PATH (e.g. CI pre-installed venv), use it directly.+# Otherwise fall back to uv run so local dev works without a pre-built venv.+if command -v mitmdump >/dev/null 2>&1 && mitmdump --version >/dev/null 2>&1; then+ exec mitmdump \+ -s "${SCRIPT_DIR}/mitm_replay.py" \+ --listen-port "${PROXY_PORT}" \+ --set connection_strategy=lazy \+ --set upstream_cert=false+else+ exec uv run --with-requirements "${SCRIPT_DIR}/requirements.txt" \+ mitmdump \+ -s "${SCRIPT_DIR}/mitm_replay.py" \+ --listen-port "${PROXY_PORT}" \+ --set connection_strategy=lazy \+ --set upstream_cert=false+fi