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

ci: introduce replay mechanism in cypress tests (#12332)

CHALLA NISHANTH BABU6f3bf29b45d8
diff --git a/.github/workflows/cypress-tests-runner.yml b/.github/workflows/cypress-tests-runner.yml
index 9c68436b83..511e8453d7 100644
--- a/.github/workflows/cypress-tests-runner.yml
+++ b/.github/workflows/cypress-tests-runner.yml
@@ -8,6 +8,7 @@ on:
permissions:
contents: read
+ actions: read
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
@@ -26,6 +27,8 @@ 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_PAYOUTS_CONNECTORS: "adyenplatform wise"
RUST_BACKTRACE: short
RUSTUP_MAX_RETRIES: 10
RUN_TESTS: ${{ ((github.event_name == 'pull_request') && (github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name)) || (github.event_name == 'merge_group')}}
@@ -41,14 +44,14 @@ jobs:
- name: Generate a token
if: ${{ github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name }}
id: generate_token
- uses: actions/create-github-app-token@v1
+ uses: actions/create-github-app-token@v3
with:
app-id: ${{ secrets.HYPERSWITCH_BOT_APP_ID }}
private-key: ${{ secrets.HYPERSWITCH_BOT_APP_PRIVATE_KEY }}
- name: Checkout repository with token
if: ${{ github.event.pull_request.head.repo.full_name == github.event.pull_request.base.repo.full_name }}
- uses: actions/checkout@v5
+ uses: actions/checkout@v6
with:
fetch-depth: 0
ref: ${{ github.event.pull_request.head.ref }}
@@ -56,10 +59,10 @@ jobs:
- name: Checkout repository for fork
if: ${{ github.event.pull_request.head.repo.full_name != github.event.pull_request.base.repo.full_name }}
- uses: actions/checkout@v5
+ uses: actions/checkout@v6
- name: Install Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@v6
with:
node-version: "24"
@@ -110,7 +113,7 @@ jobs:
- name: Checkout repository
if: ${{ env.RUN_TESTS == 'true' }}
- uses: actions/checkout@v5
+ uses: actions/checkout@v6
- name: Install mold linker
if: ${{ env.RUN_TESTS == 'true' }}
@@ -200,8 +203,8 @@ jobs:
name: Run mandatory Cypress tests
needs: [build-hyperswitch, prepare-mandatory-matrix]
if: |
- (github.event_name == 'merge_group' ||
- (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'S-test-ready')))
+ github.event_name == 'merge_group' ||
+ (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'S-test-ready'))
permissions:
pull-requests: write
# use hyperswitch-runners-merge for merge queue level checks
@@ -252,7 +255,7 @@ jobs:
- name: Checkout repository
if: ${{ env.RUN_TESTS == 'true' }}
- uses: actions/checkout@v5
+ uses: actions/checkout@v6
- name: Install Rust
if: ${{ env.RUN_TESTS == 'true' }}
@@ -313,7 +316,7 @@ jobs:
- name: Install Diesel CLI
if: ${{ env.RUN_TESTS == 'true' }}
- uses: baptiste0928/[email protected]
+ uses: baptiste0928/[email protected]
with:
crate: diesel_cli
features: postgres
@@ -328,7 +331,7 @@ jobs:
- name: Install Node.js
if: ${{ env.RUN_TESTS == 'true' }}
- uses: actions/setup-node@v4
+ uses: actions/setup-node@v6
with:
node-version: "24"
@@ -370,6 +373,8 @@ jobs:
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_PPC_KEY: ${{ secrets.APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY }}
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE }}
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT_KEY: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE_KEY }}
+ # Apply seeded Superposition config quickly in CI (default is 300s).
+ ROUTER__SUPERPOSITION__POLLING_INTERVAL: 10
SERVER_LOG_PATH: ${{ github.workspace }}/server-logs.txt
run: |
# Start the server in the background
@@ -425,11 +430,11 @@ jobs:
mandatory-cypress-tests-consolidated-result:
name: Mandatory Cypress Tests — Consolidated Result
needs: [mandatory-cypress-tests]
- runs-on: ubuntu-latest
if: |
(github.event_name == 'merge_group' ||
(github.event_name == 'pull_request' &&
contains(github.event.pull_request.labels.*.name, 'S-test-ready'))) && !cancelled()
+ runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
@@ -543,7 +548,7 @@ jobs:
steps:
- name: Checkout repository
- uses: actions/checkout@v5
+ uses: actions/checkout@v6
- name: Install Rust
uses: dtolnay/rust-toolchain@master
@@ -596,7 +601,7 @@ jobs:
echo "CYPRESS_ADMINAPIKEY=${LOCAL_ADMIN_API_KEY}" >> $GITHUB_ENV
- name: Install Diesel CLI
- uses: baptiste0928/[email protected]
+ uses: baptiste0928/[email protected]
with:
crate: diesel_cli
features: postgres
@@ -609,7 +614,7 @@ jobs:
checksum: true
- name: Install Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@v6
with:
node-version: "24"
@@ -637,6 +642,8 @@ jobs:
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_PPC_KEY: ${{ secrets.APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY }}
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE }}
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT_KEY: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE_KEY }}
+ # Apply seeded Superposition config quickly in CI (default is 300s).
+ ROUTER__SUPERPOSITION__POLLING_INTERVAL: 10
SERVER_LOG_PATH: ${{ github.workspace }}/server-logs.txt
run: |
# Start the server in the background
@@ -709,6 +716,460 @@ jobs:
exit 1
fi
+ prepare-mock-matrix:
+ name: Prepare Mock Connectors matrix
+ if: |
+ github.event_name == 'merge_group' ||
+ (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'S-test-ready'))
+ runs-on: ubuntu-latest
+ outputs:
+ mock-matrix: ${{ steps.set-mock-matrix.outputs.matrix }}
+ steps:
+ - name: Set matrix for mock connector batches
+ id: set-mock-matrix
+ shell: bash
+ run: |
+ {
+ echo "matrix<<EOF"
+ echo '{
+ "batch": [
+ {
+ "name": "mock-payouts",
+ "payments_connectors": "",
+ "payouts_connectors": "'"${MOCK_PAYOUTS_CONNECTORS}"'",
+ "platform_connectors": "",
+ "parallel": 2,
+ "report_artifact_name": "cypress-mock-test-results-payouts",
+ "server_logs_artifact": "mock-server-logs-payouts"
+ },
+ {
+ "name": "mock-payments",
+ "payments_connectors": "'"${MOCK_PAYMENTS_CONNECTORS}"'",
+ "payouts_connectors": "",
+ "platform_connectors": "",
+ "parallel": 5,
+ "report_artifact_name": "cypress-mock-test-results-payments",
+ "server_logs_artifact": "mock-server-logs-payments"
+ }
+ ]
+ }'
+ echo "EOF"
+ } >> "$GITHUB_OUTPUT"
+
+ mitm-cassette-replay-cypress-tests:
+ name: Run MITM mock Cypress tests (${{ matrix.batch.name }})
+ needs: [build-hyperswitch, prepare-mock-matrix]
+ if: |
+ (github.event_name == 'merge_group' ||
+ (github.event_name == 'pull_request' &&
+ contains(github.event.pull_request.labels.*.name, 'S-test-ready'))) && !cancelled()
+ runs-on: hyperswitch-runners
+ strategy:
+ fail-fast: false
+ matrix: ${{ fromJson(needs.prepare-mock-matrix.outputs['mock-matrix']) }}
+ env:
+ RUSTC_WRAPPER: sccache
+
+ services:
+ redis:
+ image: "public.ecr.aws/docker/library/redis:alpine"
+ options: >-
+ --health-cmd "redis-cli ping"
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ ports:
+ - 6379:6379
+ postgres:
+ image: "public.ecr.aws/docker/library/postgres:alpine"
+ env:
+ POSTGRES_USER: db_user
+ POSTGRES_PASSWORD: db_pass
+ POSTGRES_DB: hyperswitch_db
+ options: >-
+ --health-cmd pg_isready
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+ ports:
+ - 5432:5432
+ superposition:
+ image: ghcr.io/juspay/superposition-demo:0.102.0
+ env:
+ API_HOSTNAME: http://localhost:8081
+ REDIS_URL: redis://redis:6379
+ ports:
+ - 8081:8080
+
+ steps:
+ - name: Skip tests for PRs from forks
+ if: ${{ env.RUN_TESTS == 'false' }}
+ shell: bash
+ run: echo 'Skipping tests for PRs from forks'
+
+ - name: Checkout repository
+ if: ${{ env.RUN_TESTS == 'true' }}
+ uses: actions/checkout@v6
+
+ - name: Install Rust
+ if: ${{ env.RUN_TESTS == 'true' }}
+ uses: dtolnay/rust-toolchain@master
+ with:
+ toolchain: stable 2 weeks ago
+ components: rustfmt
+
+ - name: Install sccache
+ if: ${{ env.RUN_TESTS == 'true' }}
+ uses: taiki-e/install-action@v2
+ with:
+ tool: sccache
+ checksum: true
+
+ - name: Download hyperswitch server artifact
+ if: ${{ env.RUN_TESTS == 'true' }}
+ uses: actions/download-artifact@v8
+ with:
+ name: hyperswitch-server
+ path: target/debug
+
+ - name: Make server executable
+ if: ${{ env.RUN_TESTS == 'true' }}
+ run: chmod +x target/debug/router
+
+ - name: Download Encrypted TOML from S3 and Decrypt
+ if: ${{ env.RUN_TESTS == 'true' }}
+ env:
+ AWS_ACCESS_KEY_ID: ${{ secrets.CONNECTOR_CREDS_AWS_ACCESS_KEY_ID }}
+ AWS_REGION: ${{ secrets.CONNECTOR_CREDS_AWS_REGION }}
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.CONNECTOR_CREDS_AWS_SECRET_ACCESS_KEY }}
+ CONNECTOR_AUTH_PASSPHRASE: ${{ secrets.CONNECTOR_AUTH_PASSPHRASE }}
+ CONNECTOR_CREDS_S3_BUCKET_URI: ${{ secrets.CONNECTOR_CREDS_S3_BUCKET_URI }}
+ DESTINATION_FILE_NAME: "creds.json.gpg"
+ S3_SOURCE_FILE_NAME: "68bba6ea-3c75-440f-9c4b-00a30ecbb79d.json.gpg"
+ shell: bash
+ run: |
+ mkdir -p ".github/secrets" ".github/test"
+ aws s3 cp "${CONNECTOR_CREDS_S3_BUCKET_URI}/${S3_SOURCE_FILE_NAME}" ".github/secrets/${DESTINATION_FILE_NAME}"
+ gpg --quiet --batch --yes --decrypt --passphrase="${CONNECTOR_AUTH_PASSPHRASE}" --output ".github/test/creds.json" ".github/secrets/${DESTINATION_FILE_NAME}"
+
+ - name: Set paths in env
+ if: ${{ env.RUN_TESTS == 'true' }}
+ shell: bash
+ run: |
+ echo "CYPRESS_CONNECTOR_AUTH_FILE_PATH=${{ github.workspace }}/.github/test/creds.json" >> $GITHUB_ENV
+ echo "SERVER_LOG_PATH=${{ github.workspace }}/server-logs.txt" >> $GITHUB_ENV
+
+ - name: Fetch keys
+ if: ${{ env.RUN_TESTS == 'true' }}
+ env:
+ TOML_PATH: "./config/development.toml"
+ run: |
+ LOCAL_ADMIN_API_KEY=$(yq '.secrets.admin_api_key' ${TOML_PATH})
+ echo "CYPRESS_ADMINAPIKEY=${LOCAL_ADMIN_API_KEY}" >> $GITHUB_ENV
+
+ - name: Install Diesel CLI
+ if: ${{ env.RUN_TESTS == 'true' }}
+ uses: baptiste0928/[email protected]
+ with:
+ crate: diesel_cli
+ features: postgres
+ args: --no-default-features
+
+ - name: Install Just
+ if: ${{ env.RUN_TESTS == 'true' }}
+ uses: taiki-e/install-action@v2
+ with:
+ tool: just
+ checksum: true
+
+ - name: Install Node.js
+ if: ${{ env.RUN_TESTS == 'true' }}
+ uses: actions/setup-node@v6
+ with:
+ node-version: "24"
+
+ - name: Install Cypress and dependencies
+ if: ${{ env.RUN_TESTS == 'true' }}
+ run: |
+ npm ci --prefix ./cypress-tests
+
+ - name: Run database migrations
+ if: ${{ env.RUN_TESTS == 'true' }}
+ shell: bash
+ env:
+ DATABASE_URL: postgres://db_user:db_pass@localhost:5432/hyperswitch_db
+ run: just migrate run --locked-schema
+
+ - name: Insert card info into the database
+ if: ${{ env.RUN_TESTS == 'true' }}
+ run: |
+ PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --command "\copy cards_info FROM '.github/data/cards_info.csv' DELIMITER ',' CSV HEADER;"
+
+ - name: Insert GSM info into the database
+ if: ${{ env.RUN_TESTS == 'true' }}
+ run: |
+ PGPASSWORD=db_pass psql --host=localhost --port=5432 --username=db_user --dbname=hyperswitch_db --command "\copy gateway_status_map FROM '.github/data/gateway_status_map.csv' DELIMITER ',' CSV HEADER;"
+
+ - name: Seed Superposition
+ if: ${{ env.RUN_TESTS == 'true' }}
+ env:
+ SUPERPOSITION_URL: "http://localhost:8081"
+ SEED_FILE: "./config/superposition_seed.toml"
+ WORKSPACE_ID: "dev"
+ ORG_ID: "localorg"
+ run: bash scripts/seed_superposition.sh
+
+ - name: Download cassettes from S3
+ if: ${{ env.RUN_TESTS == 'true' }}
+ env:
+ AWS_ACCESS_KEY_ID: ${{ secrets.CONNECTOR_CREDS_AWS_ACCESS_KEY_ID }}
+ AWS_REGION: ${{ secrets.CONNECTOR_CREDS_AWS_REGION }}
+ AWS_SECRET_ACCESS_KEY: ${{ secrets.CONNECTOR_CREDS_AWS_SECRET_ACCESS_KEY }}
+ CONNECTOR_MOCK_DATA_S3_BUCKET_URI: ${{ secrets.CONNECTOR_MOCK_DATA_S3_BUCKET_URI }}
+ CONNECTOR_AUTH_PASSPHRASE: ${{ secrets.CONNECTOR_AUTH_PASSPHRASE }}
+ shell: bash
+ run: |
+ # S3 layout: {bucket}/{connector}/{type}.tar.gz.gpg
+ # Each tarball must extract its files under {connector}/... so the
+ # replay store finds them at cypress-tests/mitm-proxy/captures/{connector}/.
+ # We accept tarballs created either way (with or without a leading
+ # {connector}/ component) and normalise the on-disk layout here so
+ # a misformed tarball doesn't silently produce zero cassettes.
+ set -euo pipefail
+ mkdir -p "cypress-tests/mitm-proxy/captures"
+
+ fetch_cassettes() {
+ local connector="$1"
+ local type="$2"
+ local src="${CONNECTOR_MOCK_DATA_S3_BUCKET_URI}/${connector}/${type}.tar.gz.gpg"
+ local gpg_path="/tmp/${connector}-${type}-cassettes.tar.gz.gpg"
+ local tar_path="/tmp/${connector}-${type}-cassettes.tar.gz"
+ local dest="cypress-tests/mitm-proxy/captures/${connector}"
+
+ echo "→ ${connector}/${type}: ${src}"
+ aws s3 cp "${src}" "${gpg_path}"
+ echo " encrypted size: $(stat -c %s "${gpg_path}" 2>/dev/null || stat -f %z "${gpg_path}") bytes"
+
+ gpg --quiet --batch --yes --decrypt \
+ --passphrase="${CONNECTOR_AUTH_PASSPHRASE}" \
+ --output "${tar_path}" "${gpg_path}"
+ echo " decrypted size: $(stat -c %s "${tar_path}" 2>/dev/null || stat -f %z "${tar_path}") bytes"
+
+ # Stage into a temp dir so we can normalise the prefix structure
+ # before placing files under captures/{connector}/.
+ local stage
+ stage="$(mktemp -d)"
+ tar -xzf "${tar_path}" -C "${stage}"
+ echo " tarball top-level entries: $(ls -A "${stage}" | tr '\n' ' ')"
+
+ mkdir -p "${dest}"
+ # If the tarball wrapped its contents in {connector}/, strip that
+ # one level. Otherwise treat the tarball root as already being
+ # {connector}/'s contents.
+ if [ -d "${stage}/${connector}" ]; then
+ cp -R "${stage}/${connector}/." "${dest}/"
+ else
+ cp -R "${stage}/." "${dest}/"
+ fi
+ rm -rf "${stage}"
+
+ local count
+ count="$(find "${dest}" -name '*.json' | wc -l | tr -d ' ')"
+ echo " extracted: ${count} cassettes → ${dest}/"
+ if [ "${count}" -eq 0 ]; then
+ echo "::error::No cassettes for ${connector}/${type}. Tarball is empty or has an unexpected internal layout; re-record and re-upload."
+ return 1
+ fi
+ }
+
+ for connector in ${{ matrix.batch.platform_connectors }}; do
+ [ -z "${connector}" ] && continue
+ fetch_cassettes "${connector}" "platform"
+ done
+
+ for connector in ${{ matrix.batch.payments_connectors }}; do
+ [ -z "${connector}" ] && continue
+ fetch_cassettes "${connector}" "payment"
+ done
+
+ for connector in ${{ matrix.batch.payouts_connectors }}; do
+ [ -z "${connector}" ] && continue
+ fetch_cassettes "${connector}" "payout"
+ done
+
+ - name: Install uv
+ if: ${{ env.RUN_TESTS == 'true' }}
+ uses: astral-sh/[email protected]
+
+ - name: Install mitmproxy dependencies
+ if: ${{ env.RUN_TESTS == 'true' }}
+ shell: bash
+ env:
+ # Use the runner's OS trust store instead of uv's bundled webpki roots.
+ # Required when the runner sits behind a TLS-intercepting proxy whose
+ # internal CA is installed system-wide but not in uv's static bundle.
+ UV_SYSTEM_CERTS: "true"
+ run: |
+ # Create an isolated venv for mitmproxy so we don't touch the
+ # runner's system Python (PEP 668 / externally-managed-environment).
+ uv venv --system-certs "${{ github.workspace }}/.venv-mitm"
+ uv pip install --system-certs --python "${{ github.workspace }}/.venv-mitm/bin/python" \
+ -r cypress-tests/mitm-proxy/requirements.txt
+ # Expose the venv to subsequent steps (mitmdump cert gen, start_replay.sh).
+ echo "${{ github.workspace }}/.venv-mitm/bin" >> "$GITHUB_PATH"
+ "${{ github.workspace }}/.venv-mitm/bin/mitmdump" --version
+
+ - name: Generate mitmproxy CA cert
+ if: ${{ env.RUN_TESTS == 'true' }}
+ shell: bash
+ run: |
+ timeout 5 mitmdump --listen-port 18888 >/tmp/mitm-certgen.log 2>&1 || true
+ test -f "$HOME/.mitmproxy/mitmproxy-ca-cert.pem"
+
+ - name: Setup Local Server
+ if: ${{ env.RUN_TESTS == 'true' }}
+ env:
+ ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_PPC: ${{ secrets.APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE }}
+ ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_PPC_KEY: ${{ secrets.APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY }}
+ ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE }}
+ ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT_KEY: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE_KEY }}
+ # Apply seeded Superposition config quickly in CI (default is 300s).
+ ROUTER__SUPERPOSITION__POLLING_INTERVAL: 10
+ ROUTER__PROXY__HTTPS_URL: "http://127.0.0.1:8888"
+ ROUTER__PROXY__HTTP_URL: "http://127.0.0.1:8888"
+ ROUTER__PROXY__MITM_ENABLED: "true"
+ ROUTER__TRACE_HEADER__ID_REUSE_STRATEGY: "use_incoming"
+ ROUTER__SERVER__WORKERS: 4
+ SERVER_LOG_PATH: ${{ github.workspace }}/server-logs.txt
+ shell: bash
+ run: |
+ MITM_CERT=$(sed 's/$/\\r\\n/' "$HOME/.mitmproxy/mitmproxy-ca-cert.pem" | tr -d '\n')
+ export ROUTER__PROXY__MITM_CA_CERTIFICATE="$MITM_CERT"
+
+ target/debug/router >> "${SERVER_LOG_PATH}" 2>&1 &
+ SERVER_PID=$!
+ echo "PID=${SERVER_PID}" >> $GITHUB_ENV
+
+ COUNT=0
+ while ! nc -z localhost 8080; do
+ if [ $COUNT -gt 12 ]; then
+ echo "Server did not start within a reasonable time. Exiting."
+ kill ${SERVER_PID}
+ exit 1
+ fi
+ COUNT=$((COUNT+1))
+ sleep 10
+ done
+
+ - name: Start mitmproxy replay
+ if: ${{ env.RUN_TESTS == 'true' }}
+ shell: bash
+ env:
+ CAPTURE_DIR: ${{ github.workspace }}/cypress-tests/mitm-proxy/captures
+ ADMIN_PORT: "8001"
+ PROXY_PORT: "8888"
+ run: |
+ nohup bash cypress-tests/mitm-proxy/start_replay.sh \
+ > "${{ github.workspace }}/mitm-replay.log" 2>&1 &
+ MITM_PID=$!
+ echo "MITM_PID=${MITM_PID}" >> $GITHUB_ENV
+
+ COUNT=0
+ while ! nc -z localhost 8888; do
+ if [ $COUNT -gt 15 ]; then
+ echo "mitmdump did not start within a reasonable time. Exiting."
+ kill ${MITM_PID}
+ exit 1
+ fi
+ COUNT=$((COUNT+1))
+ sleep 2
+ done
+ echo "mitmproxy replay started (PID=${MITM_PID})"
+
+ - name: Run Cypress tests
+ if: ${{ env.RUN_TESTS == 'true' }}
+ env:
+ CYPRESS_BASEURL: "http://localhost:8080"
+ PAYMENTS_CONNECTORS: "${{ matrix.batch.payments_connectors }}"
+ PAYOUTS_CONNECTORS: "${{ matrix.batch.payouts_connectors }}"
+ PLATFORM_CONNECTORS: "${{ matrix.batch.platform_connectors }}"
+ CYPRESS_MOCK_SERVER: "true"
+ CYPRESS_IS_PROXY_ENABLED: "true"
+ # 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"
+ shell: bash -leuo pipefail {0}
+ run: |
+ scripts/execute_cypress.sh --parallel ${{ matrix.batch.parallel }}
+
+ kill "${{ env.PID }}"
+ kill "${{ env.MITM_PID }}" 2>/dev/null || true
+
+ - name: Upload MITM replay logs on failure
+ if: env.RUN_TESTS == 'true' && failure()
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ matrix.batch.server_logs_artifact }}-mitm-replay
+ path: ${{ github.workspace }}/mitm-replay.log
+ if-no-files-found: ignore
+ retention-days: 1
+
+ - name: Upload server logs on failure
+ if: env.RUN_TESTS == 'true' && failure()
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ matrix.batch.server_logs_artifact }}
+ path: ${{ env.SERVER_LOG_PATH }}
+ if-no-files-found: ignore
+ retention-days: 1
+
+ - name: Upload Cypress test results
+ if: env.RUN_TESTS == 'true' && failure()
+ uses: actions/upload-artifact@v7
+ with:
+ name: ${{ matrix.batch.report_artifact_name }}
+ path: |
+ cypress-tests/cypress/reports/
+ retention-days: 1
+
+ mitm-cassette-replay-cypress-tests-consolidated-result:
+ name: MITM Mock Cypress Tests — Consolidated Result
+ needs: [mitm-cassette-replay-cypress-tests]
+ if: |
+ github.event_name == 'merge_group' ||
+ (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'S-test-ready'))
+ runs-on: ubuntu-latest
+ permissions:
+ pull-requests: write
+ steps:
+ - name: Evaluate Matrix Results
+ shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ RESULT="${{ needs.mitm-cassette-replay-cypress-tests.result }}"
+ RUN_TESTS_VAL="${{ env.RUN_TESTS }}"
+
+ echo "mitm-cassette-replay-cypress-tests result: $RESULT"
+ echo "Run tests env: $RUN_TESTS_VAL"
+
+ if [ "$RUN_TESTS_VAL" == "false" ]; then
+ echo "Tests were skipped (Fork PR). Marking as success."
+ exit 0
+ fi
+
+ if [ "$RESULT" == "success" ]; then
+ echo "All MITM mock tests passed."
+ exit 0
+ else
+ echo "MITM mock tests failed."
+ if [ "${{ github.event_name }}" != "merge_group" ]; then
+ echo "Removing 'S-test-ready' label from the PR."
+ gh pr edit ${{ github.event.pull_request.number }} --remove-label "S-test-ready" --repo ${{ github.repository }}
+ fi
+ exit 1
+ fi
+
prepare-optional-matrix:
name: Prepare Optional Connectors matrix to run cypress tests
if: false
@@ -788,7 +1249,7 @@ jobs:
steps:
- name: Checkout repository
- uses: actions/checkout@v5
+ uses: actions/checkout@v6
- name: Install Rust
uses: dtolnay/rust-toolchain@master
@@ -841,7 +1302,7 @@ jobs:
echo "CYPRESS_ADMINAPIKEY=${LOCAL_ADMIN_API_KEY}" >> $GITHUB_ENV
- name: Install Diesel CLI
- uses: baptiste0928/[email protected]
+ uses: baptiste0928/[email protected]
with:
crate: diesel_cli
features: postgres
@@ -854,7 +1315,7 @@ jobs:
checksum: true
- name: Install Node.js
- uses: actions/setup-node@v4
+ uses: actions/setup-node@v6
with:
node-version: "24"
@@ -890,6 +1351,8 @@ jobs:
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_PPC_KEY: ${{ secrets.APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY }}
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE }}
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT_KEY: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE_KEY }}
+ # Apply seeded Superposition config quickly in CI (default is 300s).
+ ROUTER__SUPERPOSITION__POLLING_INTERVAL: 10
run: |
touch "${{ env.SERVER_LOG_PATH }}"
# Start the server in the background
@@ -987,7 +1450,7 @@ jobs:
- name: Checkout repository
if: ${{ env.RUN_TESTS == 'true' }}
- uses: actions/checkout@v5
+ uses: actions/checkout@v6
- name: Download hyperswitch server artifact
if: ${{ env.RUN_TESTS == 'true' }}
@@ -1030,7 +1493,7 @@ jobs:
- name: Install Diesel CLI
if: ${{ env.RUN_TESTS == 'true' }}
- uses: baptiste0928/[email protected]
+ uses: baptiste0928/[email protected]
with:
crate: diesel_cli
features: postgres
@@ -1045,7 +1508,7 @@ jobs:
- name: Install Node.js
if: ${{ env.RUN_TESTS == 'true' }}
- uses: actions/setup-node@v4
+ uses: actions/setup-node@v6
with:
node-version: "24"
@@ -1112,6 +1575,8 @@ jobs:
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_PPC_KEY: ${{ secrets.APPLE_PAY_PAYMENT_PROCESSING_CERTIFICATE_KEY }}
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE }}
ROUTER__APPLEPAY_DECRYPT_KEYS__APPLE_PAY_MERCHANT_CERT_KEY: ${{ secrets.APPLE_PAY_MERCHANT_CERTIFICATE_KEY }}
+ # Apply seeded Superposition config quickly in CI (default is 300s).
+ ROUTER__SUPERPOSITION__POLLING_INTERVAL: 10
run: |
# Set base URLs for alpha connectors to point to mock servers
for connector in ${{ env.ALPHA_PAYMENTS_CONNECTORS }}; do
@@ -1214,7 +1679,7 @@ jobs:
- name: Checkout repository
if: ${{ env.RUN_TESTS == 'true' }}
- uses: actions/checkout@v5
+ uses: actions/checkout@v6
- name: Download Encrypted TOML from S3 and Decrypt
if: ${{ env.RUN_TESTS == 'true' }}
@@ -1275,7 +1740,7 @@ jobs:
- name: Install Diesel CLI
if: ${{ env.RUN_TESTS == 'true' }}
- uses: baptiste0928/[email protected]
+ uses: baptiste0928/[email protected]
with:
crate: diesel_cli
features: postgres
@@ -1297,7 +1762,7 @@ jobs:
- name: Install Node.js
if: ${{ env.RUN_TESTS == 'true' }}
- uses: actions/setup-node@v4
+ uses: actions/setup-node@v6
with:
node-version: "24"
@@ -1343,6 +1808,8 @@ jobs:
if: ${{ env.RUN_TESTS == 'true' }}
env:
LLVM_PROFILE_FILE: "coverage.profraw"
+ # Apply seeded Superposition config quickly in CI (default is 300s).
+ ROUTER__SUPERPOSITION__POLLING_INTERVAL: 10
run: |
# Start the server in the background
target/debug/router &
@@ -1397,7 +1864,7 @@ jobs:
run: grcov . --source-dir . --output-types lcov --output-path ${{ env.CODECOV_FILE }} --binary-path ./target/debug --keep-only "crates/*"
- name: Upload coverage reports to Codecov
- uses: codecov/codecov-action@v5
+ uses: codecov/codecov-action@v6
if: ${{ env.RUN_TESTS == 'true' && github.event_name != 'merge_group' && (success() || failure()) }}
with:
token: ${{ secrets.CODECOV_TOKEN }}
diff --git a/cypress-tests/cypress.config.js b/cypress-tests/cypress.config.js
index 1c80ca3f51..aa83fe13d7 100644
--- a/cypress-tests/cypress.config.js
+++ b/cypress-tests/cypress.config.js
@@ -9,6 +9,7 @@ let globalState;
const connectorId = process.env.CYPRESS_CONNECTOR || "service";
const screenshotsFolderName = `screenshots/${connectorId}`;
const reportName = process.env.REPORT_NAME || `${connectorId}_report`;
+const retries = process.env.CYPRESS_MOCK_SERVER === "true" ? 0 : 2;
// Get timeout multiplier from shared utility
const timeoutMultiplier = getTimeoutMultiplier();
@@ -61,7 +62,6 @@ export default defineConfig({
return config;
},
experimentalRunAllSpecs: true,
- retries: 2,
specPattern: "cypress/e2e/**/*.cy.{js,jsx,ts,tsx}",
supportFile: "cypress/support/e2e.js",
@@ -82,6 +82,7 @@ export default defineConfig({
requestTimeout: Math.round(45000 * timeoutMultiplier),
taskTimeout: Math.round(120000 * timeoutMultiplier),
screenshotsFolder: screenshotsFolderName,
+ retries: retries,
video: true,
videoCompression: 32,
videosFolder: `cypress/videos/${connectorId}`,
diff --git a/cypress-tests/cypress/e2e/configs/Payment/Utils.js b/cypress-tests/cypress/e2e/configs/Payment/Utils.js
index 80634d1871..278b267c71 100644
--- a/cypress-tests/cypress/e2e/configs/Payment/Utils.js
+++ b/cypress-tests/cypress/e2e/configs/Payment/Utils.js
@@ -431,14 +431,19 @@ export const CONNECTOR_LISTS = {
"bamboraapac",
"bankofamerica",
"billwerk",
+ "bluesnap",
"braintree",
+ "cashtocode",
"facilitapay",
"fiserv",
"fiuu",
"forte",
"globalpay",
+ "gigadat",
"jpmorgan",
+ "loonio",
"nexinets",
+ "noon",
"novalnet",
"payload",
"paypal",
@@ -450,7 +455,7 @@ export const CONNECTOR_LISTS = {
"mollie",
"zift",
],
- MANDATE_ID_TEST: ["airwallex", "payload"],
+ MANDATE_ID_TEST: ["airwallex", "payload", "gigadat", "loonio"],
// Add more exclusion lists
},
diff --git a/cypress-tests/cypress/e2e/spec/Payment/15-ZeroAuthMandate.cy.js b/cypress-tests/cypress/e2e/spec/Payment/15-ZeroAuthMandate.cy.js
index 71ed77cc84..aab3931983 100644
--- a/cypress-tests/cypress/e2e/spec/Payment/15-ZeroAuthMandate.cy.js
+++ b/cypress-tests/cypress/e2e/spec/Payment/15-ZeroAuthMandate.cy.js
@@ -5,10 +5,28 @@ import getConnectorDetails, * as utils from "../../configs/Payment/Utils";
let globalState;
describe("Card - SingleUse Mandates flow test", () => {
- before("seed global state", () => {
- cy.task("getGlobalState").then((state) => {
- globalState = new State(state);
- });
+ before("seed global state", function () {
+ let skip = false;
+
+ cy.task("getGlobalState")
+ .then((state) => {
+ globalState = new State(state);
+
+ // Skip running test against a connector that is added in the exclude list
+ if (
+ utils.shouldExcludeConnector(
+ globalState.get("connectorId"),
+ utils.CONNECTOR_LISTS.EXCLUDE.MANDATE_ID_TEST
+ )
+ ) {
+ skip = true;
+ }
+ })
+ .then(() => {
+ if (skip) {
+ this.skip();
+ }
+ });
});
after("flush global state", () => {
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index 7f34342d87..906abf8697 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -37,6 +37,22 @@ import * as RequestBodyUtils from "../utils/RequestBodyUtils";
import { isoTimeTomorrow, validateEnv } from "../utils/RequestBodyUtils.js";
import { handleRedirection } 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";
+}
+
+// Returns true (after logging a consistent skip line) when a redirection
+// command should bail out early because we're in replay mode.
+function skipRedirectionInMockServer(commandName) {
+ if (!isMockServer()) {
+ return false;
+ }
+ cy.task("cli_log", `Skipping ${commandName}: MOCK_SERVER=true`);
+ return true;
+}
+
function getOriginalConnectorId(globalState) {
return (
globalState.get("originalConnectorId") || globalState.get("connectorId")
@@ -2355,6 +2371,8 @@ Cypress.Commands.add(
}
globalState.set("paymentAmount", createPaymentBody.amount);
+ globalState.set("paymentCurrency", createPaymentBody.currency);
+ globalState.set("captureMethod", capture_method);
globalState.set("setupFutureUsage", createPaymentBody.setup_future_usage);
cy.request({
method: "POST",
@@ -3448,6 +3466,16 @@ Cypress.Commands.add(
createConfirmPaymentBody.profile_id = profile_id;
createConfirmPaymentBody.customer_id = customer_id;
+ globalState.set("captureMethod", capture_method);
+ globalState.set(
+ "paymentAmount",
+ createConfirmPaymentBody.amount || (reqData && reqData.amount)
+ );
+ globalState.set(
+ "paymentCurrency",
+ createConfirmPaymentBody.currency || (reqData && reqData.currency)
+ );
+
for (const key in reqData) {
// Skip split_payments here - it will be added conditionally below
if (key !== "split_payments") {
@@ -4379,7 +4407,6 @@ Cypress.Commands.add(
expect(response.headers["content-type"]).to.include("application/json");
if (response.status === 200) {
globalState.set("paymentID", response.body.payment_id);
-
expect(response.body.payment_method_data, "payment_method_data").to
.not.be.empty;
const expectedConnector = getOriginalConnectorName(
@@ -5001,12 +5028,33 @@ Cypress.Commands.add(
"handleRedirection",
(globalState, expectedRedirection) => {
const connectorId = globalState.get("connectorId");
- const nextActionUrl = globalState.get("nextActionUrl");
-
+ // 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) {
- throw new Error(
- `handleRedirection: nextActionUrl is not set in globalState. Confirm step may not have returned a valid next_action URL.`
+ cy.task(
+ "cli_log",
+ "handleRedirection: nextActionUrl missing — falling back to https://example.com"
);
+ 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,
+ });
+ }
+ return;
}
const expectedUrl = new URL(expectedRedirection);
@@ -5027,6 +5075,10 @@ Cypress.Commands.add(
const connectorId = globalState.get("connectorId");
const nextActionUrl = globalState.get("nextActionUrl");
+ if (skipRedirectionInMockServer("handleBankRedirectRedirection")) {
+ return;
+ }
+
const expectedUrl = new URL(expectedRedirection);
const redirectionUrl = new URL(nextActionUrl);
@@ -5050,6 +5102,10 @@ Cypress.Commands.add(
const nextActionUrl = globalState.get("nextActionUrl");
const nextActionType = globalState.get("nextActionType");
+ if (skipRedirectionInMockServer("handleBankTransferRedirection")) {
+ return;
+ }
+
const expectedUrl = new URL(expectedRedirection);
let redirectionUrl = null;
try {
@@ -5076,6 +5132,10 @@ Cypress.Commands.add(
const connectorId = globalState.get("connectorId");
const nextActionUrl = globalState.get("nextActionUrl");
+ if (skipRedirectionInMockServer("handleRewardRedirection")) {
+ return;
+ }
+
const expectedUrl = new URL(expectedRedirection);
const redirectionUrl = new URL(nextActionUrl);
@@ -5094,6 +5154,10 @@ Cypress.Commands.add(
const connectorId = globalState.get("connectorId");
const nextActionUrl = globalState.get("nextActionUrl");
+ if (skipRedirectionInMockServer("handleCryptoRedirection")) {
+ return;
+ }
+
const expectedUrl = new URL(expectedRedirection);
const redirectionUrl = new URL(nextActionUrl);
@@ -5112,6 +5176,10 @@ Cypress.Commands.add(
const connectorId = globalState.get("connectorId");
const nextActionUrl = globalState.get("nextActionUrl");
+ if (skipRedirectionInMockServer("handleWalletRedirection")) {
+ return;
+ }
+
const expectedUrl = new URL(expectedRedirection);
const redirectionUrl = new URL(nextActionUrl);
@@ -5366,6 +5434,10 @@ Cypress.Commands.add(
const connectorId = globalState.get("connectorId");
const nextActionUrl = globalState.get("nextActionUrl");
+ if (skipRedirectionInMockServer("handleUpiRedirection")) {
+ return;
+ }
+
const expectedUrl = new URL(expected_redirection);
const redirectionUrl = new URL(nextActionUrl);
@@ -5378,6 +5450,28 @@ Cypress.Commands.add(
}
);
+Cypress.Commands.add(
+ "handlePayLaterRedirection",
+ (globalState, paymentMethodType, expected_redirection) => {
+ const connectorId = globalState.get("connectorId");
+ const nextActionUrl = globalState.get("nextActionUrl");
+
+ if (skipRedirectionInMockServer("handlePayLaterRedirection")) {
+ return;
+ }
+
+ const expectedUrl = new URL(expected_redirection);
+ const redirectionUrl = new URL(nextActionUrl);
+
+ handleRedirection(
+ "pay_later",
+ { redirectionUrl, expectedUrl },
+ connectorId,
+ paymentMethodType
+ );
+ }
+);
+
Cypress.Commands.add("listCustomerPMCallTest", (globalState, order = 0) => {
const apiKey = globalState.get("apiKey");
const baseUrl = globalState.get("baseUrl");
@@ -8325,6 +8419,16 @@ Cypress.Commands.add(
createConfirmPaymentBody.profile_id = profile_id;
createConfirmPaymentBody.customer_id = customer_id;
+ globalState.set("captureMethod", capture_method);
+ globalState.set(
+ "paymentAmount",
+ createConfirmPaymentBody.amount || (reqData && reqData.amount)
+ );
+ globalState.set(
+ "paymentCurrency",
+ createConfirmPaymentBody.currency || (reqData && reqData.currency)
+ );
+
for (const key in reqData) {
createConfirmPaymentBody[key] = reqData[key];
}
diff --git a/cypress-tests/cypress/support/e2e.js b/cypress-tests/cypress/support/e2e.js
index 1ec43cd03b..23d79e7eeb 100644
--- a/cypress-tests/cypress/support/e2e.js
+++ b/cypress-tests/cypress/support/e2e.js
@@ -1,25 +1,8 @@
-// ***********************************************************
-// This example support/e2e.js is processed and
-// loaded automatically before your test files.
-//
-// This is a great place to put global configuration and
-// behavior that modifies Cypress.
-//
-// You can change the location of this file or turn off
-// automatically serving support files with the
-// 'supportFile' configuration option.
-//
-// You can read more here:
-// https://on.cypress.io/configuration
-// ***********************************************************
-
-// Import commands.js using ES2015 syntax:
import "cypress-mochawesome-reporter/register";
import "./commands";
import "./redirectionHandler";
Cypress.on("window:before:load", (win) => {
- // Add security headers
win.headers = {
"Content-Security-Policy": "default-src 'self'",
"X-Content-Type-Options": "nosniff",
@@ -27,14 +10,143 @@ Cypress.on("window:before:load", (win) => {
};
});
-// Add error handling for dynamic imports
Cypress.on("uncaught:exception", (err, runnable) => {
- // Log the error details
// eslint-disable-next-line no-console
console.error(
`Error: ${err.message}\nError occurred in: ${runnable.title}\nStack trace: ${err.stack}`
);
-
- // Return false to prevent the error from failing the test
return false;
});
+
+// MITM proxy record/replay integration, gated by IS_PROXY_ENABLED. When on,
+// each test notifies the proxy of start/end and tags every cy.request with a
+// deterministic X-Request-ID that the router propagates to connector outbounds
+// (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 PROXY_ADMIN_TIMEOUT_MS = 2000;
+const REQUEST_ID_HEADER = "X-Request-ID";
+const STEP_COUNTER_DIGITS = 3;
+
+const HTTP_METHODS = new Set([
+ "GET",
+ "POST",
+ "PUT",
+ "PATCH",
+ "DELETE",
+ "HEAD",
+ "OPTIONS",
+ "TRACE",
+ "CONNECT",
+]);
+
+// Per-test trace state, reset in beforeEach.
+let testIdHash = "";
+let stepCounter = 0;
+
+// djb2 hash as 8-char hex; deterministic so a test always reuses the same
+// request-id namespace and matches its earlier recording.
+function stableHashHex(input) {
+ let hash = 5381;
+ for (let i = 0; i < input.length; i++) {
+ hash = ((hash * 33) ^ input.charCodeAt(i)) >>> 0;
+ }
+ return hash.toString(16).padStart(8, "0");
+}
+
+// Namespace must be unique per (connector, spec, test) or rids collide on replay.
+function computeTestIdHash(connector, spec, title) {
+ return stableHashHex(`${connector}:${spec}:${title}`);
+}
+
+// Collapse cy.request's argument shapes into a single options object.
+function normalizeRequestArgs(args) {
+ if (args.length === 1) {
+ const [first] = args;
+ if (typeof first === "string") return { url: first };
+ if (first && typeof first === "object") return { ...first };
+ }
+ if (args.length === 2) {
+ const [first, second] = args;
+ if (typeof first === "string" && HTTP_METHODS.has(first.toUpperCase())) {
+ return { method: first, url: second };
+ }
+ return { url: first, body: second };
+ }
+ if (args.length === 3) {
+ return { method: args[0], url: args[1], body: args[2] };
+ }
+ return { url: args[0] };
+}
+
+// Proxy-admin calls are control traffic and must not consume a step slot.
+function isProxyAdminUrl(url) {
+ return Boolean(url) && url.startsWith(PROXY_ADMIN_URL);
+}
+
+function buildRequestId() {
+ stepCounter += 1;
+ const step = String(stepCounter).padStart(STEP_COUNTER_DIGITS, "0");
+ return `${testIdHash}-${step}`;
+}
+
+function notifyProxyTestStarted(titlePath, spec, connector) {
+ cy.request({
+ method: "POST",
+ url: `${PROXY_ADMIN_URL}/test/start`,
+ body: {
+ titlePath,
+ spec,
+ connector,
+ testIdHash,
+ },
+ failOnStatusCode: false,
+ timeout: PROXY_ADMIN_TIMEOUT_MS,
+ });
+}
+
+function notifyProxyTestEnded() {
+ cy.request({
+ method: "POST",
+ url: `${PROXY_ADMIN_URL}/test/end`,
+ failOnStatusCode: false,
+ timeout: PROXY_ADMIN_TIMEOUT_MS,
+ });
+}
+
+if (IS_PROXY_ENABLED) {
+ beforeEach(() => {
+ const { titlePath } = Cypress.currentTest;
+ const title = titlePath.join(" > ");
+ const connector = Cypress.env("CONNECTOR") || "";
+ const spec = Cypress.spec.relative;
+
+ testIdHash = computeTestIdHash(connector, spec, title);
+ stepCounter = 0;
+
+ if (PROXY_ADMIN_URL) {
+ notifyProxyTestStarted(titlePath, spec, connector);
+ }
+ });
+
+ afterEach(() => {
+ if (PROXY_ADMIN_URL) {
+ notifyProxyTestEnded();
+ }
+ });
+
+ // Tag every cy.request with a deterministic X-Request-ID for cassette matching.
+ Cypress.Commands.overwrite("request", (originalFn, ...args) => {
+ const opts = normalizeRequestArgs(args);
+
+ if (PROXY_ADMIN_URL && isProxyAdminUrl(opts.url)) {
+ return originalFn(opts);
+ }
+
+ opts.headers = {
+ ...(opts.headers || {}),
+ [REQUEST_ID_HEADER]: buildRequestId(),
+ };
+ return originalFn(opts);
+ });
+}
diff --git a/cypress-tests/mitm-proxy/.gitignore b/cypress-tests/mitm-proxy/.gitignore
new file mode 100644
index 0000000000..d27d138f38
--- /dev/null
+++ b/cypress-tests/mitm-proxy/.gitignore
@@ -0,0 +1,19 @@
+# mitmproxy runtime artifacts
+__pycache__/
+*.pyc
+*.pyo
+*.pyd
+
+#captures generated by mitmproxy
+captures/
+
+# mitmproxy cert store
+.mitmproxy/
+
+# macOS
+.DS_Store
+
+# Environment files
+.env
+.envrc
+
diff --git a/cypress-tests/mitm-proxy/mitm_capture.py b/cypress-tests/mitm-proxy/mitm_capture.py
new file mode 100644
index 0000000000..da3b29715a
--- /dev/null
+++ b/cypress-tests/mitm-proxy/mitm_capture.py
@@ -0,0 +1,306 @@
+"""
+mitmproxy capture addon.
+
+Records Hyperswitch outbound HTTP into JSON cassettes grouped by the Cypress
+test that issued the call. Grouping key is testIdHash (hash of connector +
+titlePath, sent on /test/start); every outbound carries
+X-Request-ID: {testIdHash}-{NNN}, so calls are attributed to their test even
+when they land after /test/end (e.g. async vault writes).
+
+Skipped: no/foreign X-Request-ID, or a testHash never registered via /test/start.
+"""
+
+import base64
+import glob
+import json
+import os
+import re
+import threading
+from datetime import datetime, timezone
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+from mitmproxy import http
+
+
+# ───── config ─────
+SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+OUT_DIR = os.environ.get("CAPTURE_DIR") or os.path.join(SCRIPT_DIR, "captures")
+BASE_URLS = [
+ u.strip().rstrip("/")
+ for u in os.environ.get("CAPTURE_BASE_URLS", "").split(",")
+ if u.strip()
+]
+ADMIN_PORT = int(os.environ.get("ADMIN_PORT", "8001"))
+
+_SPEC_EXTENSIONS = (".cy.js", ".cy.ts", ".spec.js", ".spec.ts")
+# rid format: 8 hex chars (hash) + "-" + 3 digits (step counter).
+_CYPRESS_RID = re.compile(r"^[0-9a-fA-F]{8}-\d{3}$")
+
+
+# ───── state ─────
+class TestContext:
+ __slots__ = ("test", "spec", "connector", "folder")
+
+ def __init__(self, test: str, spec: str, connector: str, folder: str):
+ self.test = test
+ self.spec = spec
+ self.connector = connector
+ self.folder = folder
+
+
+_lock = threading.Lock()
+_tests_by_hash: dict[str, TestContext] = {}
+# Per-rid seq counter; cleared on /test/start so retries restart at 00.
+_seq_by_rid: dict[str, int] = {}
+
+
+# ───── helpers ─────
+def safe_name(s: str) -> str:
+ return re.sub(r"[^\w\-]+", "_", s).strip("_") or "_untagged"
+
+
+def safe_spec(name: str) -> str:
+ for ext in _SPEC_EXTENSIONS:
+ if name.endswith(ext):
+ name = name[: -len(ext)]
+ break
+ name = re.sub(r"^.*?[/\\]spec[/\\]", "", name)
+ parts = [safe_name(p) for p in re.split(r"[/\\]", name) if p]
+ return os.path.join(*parts) if parts else "_untagged"
+
+
+def build_rel_path(spec: str, title_path: list) -> str:
+ """spec + titlePath → connector-relative folder."""
+ if not spec or spec == "__all":
+ spec_part = safe_name(title_path[0]) if title_path else "_untagged"
+ else:
+ spec_part = safe_spec(spec)
+ if not title_path:
+ return os.path.join(spec_part, "_untagged")
+ contexts = title_path[1:-1] if len(title_path) > 2 else []
+ if not contexts:
+ return os.path.join(spec_part, safe_name(title_path[-1]))
+ return os.path.join(spec_part, *[safe_name(c) for c in contexts])
+
+
+def url_matches(url: str) -> bool:
+ if not BASE_URLS:
+ return True
+ return any(url.startswith(b) for b in BASE_URLS)
+
+
+def hash_from_rid(rid: str) -> str:
+ return rid.split("-", 1)[0]
+
+
+def iso(ts):
+ return datetime.fromtimestamp(ts, tz=timezone.utc).isoformat() if ts else None
+
+
+def encode_body(content: bytes, content_type: str = ""):
+ if not content:
+ return {"data": None, "encoding": None, "size_bytes": 0}
+ size = len(content)
+ try:
+ text = content.decode("utf-8")
+ except UnicodeDecodeError:
+ return {
+ "data": base64.b64encode(content).decode("ascii"),
+ "encoding": "base64",
+ "size_bytes": size,
+ }
+ if "json" in content_type.lower() or text.lstrip().startswith(("{", "[")):
+ try:
+ return {"data": json.loads(text), "encoding": "json", "size_bytes": size}
+ except json.JSONDecodeError:
+ pass
+ return {"data": text, "encoding": "utf-8", "size_bytes": size}
+
+
+def wipe_test_cassettes(folder: str, test_hash: str) -> int:
+ """Delete prior cassettes for this testHash so a re-run starts clean."""
+ if not os.path.isdir(folder):
+ return 0
+ removed = 0
+ for path in glob.glob(os.path.join(folder, f"{test_hash}-*.json")):
+ try:
+ os.remove(path)
+ removed += 1
+ except OSError:
+ pass
+ return removed
+
+
+# ───── admin HTTP server ─────
+class AdminHandler(BaseHTTPRequestHandler):
+ def _send(self, code, body):
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.end_headers()
+ self.wfile.write(json.dumps(body).encode())
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length", 0))
+ raw = self.rfile.read(length).decode() if length else "{}"
+ try:
+ body = json.loads(raw)
+ except json.JSONDecodeError:
+ body = {}
+
+ if self.path == "/test/start":
+ test_id_hash = (body.get("testIdHash") or "").strip()
+ title_path = body.get("titlePath") or []
+ spec = body.get("spec") or "_untagged"
+ connector = (body.get("connector") or "").strip()
+ test = " > ".join(title_path) if title_path else "_untagged"
+
+ if not test_id_hash:
+ print(f"[capture] ▶ SKIP (no testIdHash): {test}")
+ self._send(200, {"ok": False, "reason": "missing testIdHash"})
+ return
+ if not connector:
+ print(f"[capture] ▶ SKIP (no connector): {test}")
+ self._send(200, {"ok": False, "reason": "missing connector"})
+ return
+
+ rel_path = build_rel_path(spec, title_path)
+ folder = os.path.join(OUT_DIR, connector, rel_path)
+ os.makedirs(folder, exist_ok=True)
+ wiped = wipe_test_cassettes(folder, test_id_hash)
+
+ with _lock:
+ prior = _tests_by_hash.get(test_id_hash)
+ if prior is not None and prior.folder != folder:
+ # Same hash, different folder: two specs share a titlePath,
+ # so their rids collide on replay. Fix: include spec in the
+ # Cypress-side hash (cypress/support/e2e.js).
+ print(
+ f"[capture] ⚠ COLLISION: testIdHash {test_id_hash} reused across specs\n"
+ f" was: {prior.folder}\n"
+ f" now: {folder}\n"
+ f" identical titlePath in different specs — rids will collide on replay"
+ )
+ _tests_by_hash[test_id_hash] = TestContext(
+ test=test, spec=spec, connector=connector, folder=folder,
+ )
+ # Reset this test's seq counters so the next run starts at 00.
+ for rid in [r for r in _seq_by_rid if hash_from_rid(r) == test_id_hash]:
+ del _seq_by_rid[rid]
+
+ wipe_tag = f"(wiped {wiped}) " if wiped else ""
+ print(f"[capture] ▶ START [{connector}] {wipe_tag}{test}")
+ self._send(200, {"ok": True})
+
+ elif self.path == "/test/end":
+ # No-op: map persists past /test/end for async outbounds.
+ self._send(200, {"ok": True})
+
+ elif self.path == "/status":
+ with _lock:
+ self._send(200, {
+ "tests_registered": len(_tests_by_hash),
+ "rids_in_flight": len(_seq_by_rid),
+ "out_dir": OUT_DIR,
+ "base_urls": BASE_URLS,
+ })
+
+ else:
+ self._send(404, {"error": "unknown admin path"})
+
+ def log_message(self, *_a, **_kw):
+ return
+
+
+def start_admin_server():
+ server = HTTPServer(("127.0.0.1", ADMIN_PORT), AdminHandler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ print(f"[capture] admin server http://127.0.0.1:{ADMIN_PORT}")
+
+
+# ───── mitmproxy hooks ─────
+def request(flow: http.HTTPFlow):
+ """Claim a per-rid seq slot in request order so capture and replay stay aligned."""
+ if not url_matches(flow.request.url):
+ return
+ rid = flow.request.headers.get("x-request-id", "").strip()
+ if not rid or not _CYPRESS_RID.match(rid):
+ return
+ test_hash = hash_from_rid(rid)
+ with _lock:
+ if test_hash not in _tests_by_hash:
+ return # orphan rid
+ seq = _seq_by_rid.get(rid, 0)
+ _seq_by_rid[rid] = seq + 1
+ flow.metadata["capture_seq"] = seq
+
+
+def response(flow: http.HTTPFlow):
+ # request() is the gate: if it didn't set capture_seq, this flow isn't ours.
+ seq = flow.metadata.get("capture_seq")
+ if seq is None:
+ return
+
+ rid = flow.request.headers["x-request-id"].strip()
+ test_hash = hash_from_rid(rid)
+ with _lock:
+ ctx = _tests_by_hash[test_hash]
+
+ req = flow.request
+ res = flow.response
+ duration_ms = (
+ round((res.timestamp_end - req.timestamp_start) * 1000, 2)
+ if req.timestamp_start and res.timestamp_end else None
+ )
+ req_body = encode_body(req.content, req.headers.get("content-type", ""))
+ res_body = encode_body(res.content, res.headers.get("content-type", ""))
+
+ record = {
+ "captured_at": iso(req.timestamp_start) or datetime.now(timezone.utc).isoformat(),
+ "test": ctx.test,
+ "spec": ctx.spec,
+ "connector": ctx.connector,
+ "request_id": rid,
+ "sequence": seq,
+ "timing": {
+ "request_started_at": iso(req.timestamp_start),
+ "response_completed_at": iso(res.timestamp_end),
+ "duration_ms": duration_ms,
+ },
+ "request": {
+ "http_version": req.http_version,
+ "method": req.method,
+ "url": req.url,
+ "scheme": req.scheme,
+ "host": req.host,
+ "path": req.path.split("?", 1)[0],
+ "query": dict(req.query.items(multi=True)) if req.query else {},
+ "headers": dict(req.headers),
+ "body": req_body["data"],
+ "body_encoding": req_body["encoding"],
+ "body_size_bytes": req_body["size_bytes"],
+ },
+ "response": {
+ "http_version": res.http_version,
+ "status": res.status_code,
+ "reason": res.reason,
+ "headers": dict(res.headers),
+ "body": res_body["data"],
+ "body_encoding": res_body["encoding"],
+ "body_size_bytes": res_body["size_bytes"],
+ },
+ }
+
+ out_path = os.path.join(ctx.folder, f"{rid}-{seq:02d}.json")
+ with open(out_path, "w") as f:
+ json.dump(record, f, indent=2)
+
+ print(
+ f"[capture] {req.method} {req.url} → {res.status_code} "
+ f"({duration_ms}ms) rid={rid} seq={seq:02d} → {out_path}"
+ )
+
+
+# ───── boot ─────
+start_admin_server()
+print(f"[capture] base URLs {BASE_URLS or '(none — capturing all)'}")
+print(f"[capture] output dir {OUT_DIR}")
diff --git a/cypress-tests/mitm-proxy/mitm_replay.py b/cypress-tests/mitm-proxy/mitm_replay.py
new file mode 100644
index 0000000000..101704185d
--- /dev/null
+++ b/cypress-tests/mitm-proxy/mitm_replay.py
@@ -0,0 +1,225 @@
+"""
+mitmproxy replay addon.
+
+Serves cassettes recorded by mitm_capture.py back to Hyperswitch on its
+outbound connector calls. Match key is x-request-id alone; cassettes sharing a
+rid are served in capture order via a per-rid cursor, reset on /test/start so
+Cypress retries replay from the start.
+
+Permissive (default): MISS / unknown-rid → live connector.
+Strict (REPLAY_STRICT=1): MISS / unknown-rid → synthetic 599, never live.
+
+Run: mitmdump -s mitm_replay.py --listen-port 8888
+"""
+
+import base64
+import glob
+import json
+import os
+import threading
+from collections import defaultdict
+from http.server import BaseHTTPRequestHandler, HTTPServer
+
+from mitmproxy import http
+
+
+# ───── config ─────
+SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
+CAPTURE_DIR = os.environ.get("CAPTURE_DIR") or os.path.join(SCRIPT_DIR, "captures")
+ADMIN_PORT = int(os.environ.get("ADMIN_PORT", "8001"))
+STRICT_MODE = os.environ.get("REPLAY_STRICT", "").strip().lower() in (
+ "1", "true", "yes", "on",
+)
+
+# Headers mitmproxy manages itself — don't replay them.
+_RESERVED_HEADERS = frozenset({"content-length", "transfer-encoding", "connection"})
+
+
+def hash_from_rid(rid: str) -> str:
+ return rid.split("-", 1)[0] if "-" in rid else rid
+
+
+# ───── cassette store ─────
+class CassetteStore:
+ """Cassettes indexed by rid → ordered responses, served via a per-rid
+ cursor that resets on /test/start (clean Cypress retry replay)."""
+
+ def __init__(self, capture_dir: str):
+ self._capture_dir = capture_dir
+ self._cassettes: dict[str, list[dict]] = defaultdict(list)
+ self._cursor: dict[str, int] = {}
+ self._lock = threading.Lock()
+
+ def load(self) -> None:
+ """Load all cassettes from disk into rid → [response, …]."""
+ pattern = os.path.join(self._capture_dir, "**", "*.json")
+ # Collect by rid, then sort each rid's list by the "sequence" field
+ # (robust against legacy filenames without the seq suffix).
+ by_rid: dict[str, list[tuple[int, dict]]] = defaultdict(list)
+ skipped = 0
+ for fpath in glob.glob(pattern, recursive=True):
+ try:
+ with open(fpath) as f:
+ record = json.load(f)
+ except (OSError, json.JSONDecodeError):
+ skipped += 1
+ continue
+ rid = (record.get("request_id") or "").strip()
+ if not rid or "response" not in record:
+ skipped += 1
+ continue
+ seq = record.get("sequence", 0)
+ by_rid[rid].append((seq, record["response"]))
+
+ for rid, entries in by_rid.items():
+ entries.sort(key=lambda e: e[0])
+ self._cassettes[rid] = [r for _, r in entries]
+
+ total = sum(len(v) for v in self._cassettes.values())
+ print(f"[replay] loaded {total} cassettes from {self._capture_dir}/")
+ print(f"[replay] indexed {len(self._cassettes)} unique rids")
+ if skipped:
+ print(f"[replay] skipped {skipped} cassettes (malformed or no rid)")
+
+ def serve(self, rid: str) -> dict | None:
+ """Pop the next cassette for ``rid`` (FIFO via per-rid cursor)."""
+ with self._lock:
+ cassettes = self._cassettes.get(rid)
+ if not cassettes:
+ return None
+ cursor = self._cursor.get(rid, 0)
+ if cursor >= len(cassettes):
+ return None
+ self._cursor[rid] = cursor + 1
+ return cassettes[cursor]
+
+ def reset_for_hash(self, test_hash: str) -> int:
+ """Rewind cursors for every rid whose prefix matches this hash."""
+ prefix = f"{test_hash}-"
+ with self._lock:
+ keys = [r for r in self._cursor if r.startswith(prefix)]
+ for k in keys:
+ del self._cursor[k]
+ return len(keys)
+
+
+_store = CassetteStore(CAPTURE_DIR)
+
+
+# ───── response materialisation ─────
+def _decode_body(body, encoding):
+ if encoding == "json":
+ return json.dumps(body, separators=(",", ":")).encode("utf-8")
+ if encoding == "base64":
+ return base64.b64decode(body)
+ return (body or "").encode("utf-8")
+
+
+def _build_response(recorded: dict) -> http.Response:
+ headers = {
+ k: v for k, v in recorded.get("headers", {}).items()
+ if k.lower() not in _RESERVED_HEADERS
+ }
+ headers["X-Cassette"] = "HIT"
+ return http.Response.make(
+ recorded["status"],
+ _decode_body(recorded.get("body"), recorded.get("body_encoding")),
+ headers,
+ )
+
+
+def _strict_block(reason: str, tag: str) -> http.Response:
+ body = json.dumps({
+ "error": "mitm replay strict mode: connector call blocked",
+ "reason": reason,
+ }).encode("utf-8")
+ return http.Response.make(
+ 599, body, {"Content-Type": "application/json", "X-Cassette": tag},
+ )
+
+
+# ───── admin server ─────
+class AdminHandler(BaseHTTPRequestHandler):
+ """Cypress /test/start resets cursors for that test's rids; /test/end is a no-op."""
+
+ def _send(self, code, payload):
+ self.send_response(code)
+ self.send_header("Content-Type", "application/json")
+ self.end_headers()
+ self.wfile.write(json.dumps(payload).encode())
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length", 0))
+ try:
+ body = json.loads(self.rfile.read(length) or b"{}")
+ except json.JSONDecodeError:
+ body = {}
+
+ if self.path == "/test/start":
+ title = " > ".join(body.get("titlePath") or []) or "unknown"
+ test_id_hash = (body.get("testIdHash") or "").strip()
+ connector = (body.get("connector") or "").strip()
+ tag = f"[{connector}] " if connector else ""
+ reset = _store.reset_for_hash(test_id_hash) if test_id_hash else 0
+ suffix = f" (reset {reset} rid cursors)" if reset else ""
+ print(f"[replay] ▶ {tag}{title}{suffix}")
+
+ self._send(200, {"ok": True})
+
+ def log_message(self, *_a, **_kw):
+ return
+
+
+def _start_admin_server():
+ server = HTTPServer(("127.0.0.1", ADMIN_PORT), AdminHandler)
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ print(f"[replay] admin server http://127.0.0.1:{ADMIN_PORT}")
+
+
+# ───── boot ─────
+_store.load()
+_start_admin_server()
+print(f"[replay] mode {'STRICT (no live fallthrough)' if STRICT_MODE else 'permissive'}")
+
+
+# ───── mitmproxy hook ─────
+def http_connect(flow: http.HTTPFlow) -> None:
+ """Accept CONNECT tunnels locally so we can intercept the inner HTTPS;
+ request() then decides HIT / MISS / LIVE."""
+ flow.response = http.Response.make(200, b"", {})
+
+
+def request(flow: http.HTTPFlow) -> None:
+ # Gate: only handle Hyperswitch → connector outbounds (tagged x-connector).
+ if not flow.request.headers.get("x-connector", "").strip():
+ return
+
+ rid = flow.request.headers.get("x-request-id", "").strip()
+ method = flow.request.method
+ path = flow.request.path.split("?", 1)[0]
+
+ if not rid:
+ if STRICT_MODE:
+ flow.response = _strict_block(
+ f"missing x-request-id for {method} {path}", "STRICT-no-rid",
+ )
+ print(f"[replay] BLOCK no-rid {method} {path}")
+ else:
+ flow.request.headers["X-Cassette"] = "LIVE-no-rid"
+ print(f"[replay] LIVE no-rid {method} {path}")
+ return
+
+ recorded = _store.serve(rid)
+ if recorded is None:
+ if STRICT_MODE:
+ flow.response = _strict_block(
+ f"no cassette for {method} {path} (rid={rid})", "STRICT-miss",
+ )
+ print(f"[replay] BLOCK miss {method} {path} rid={rid}")
+ else:
+ flow.request.headers["X-Cassette"] = "LIVE-miss"
+ print(f"[replay] MISS {method} {path} rid={rid}")
+ return
+
+ flow.response = _build_response(recorded)
+ print(f"[replay] HIT {method} {path} rid={rid} → {recorded['status']}")
diff --git a/cypress-tests/mitm-proxy/requirements.txt b/cypress-tests/mitm-proxy/requirements.txt
new file mode 100644
index 0000000000..1b0d22d638
--- /dev/null
+++ b/cypress-tests/mitm-proxy/requirements.txt
@@ -0,0 +1 @@
+mitmproxy==12.2.3
diff --git a/cypress-tests/mitm-proxy/start_record.sh b/cypress-tests/mitm-proxy/start_record.sh
new file mode 100755
index 0000000000..6486aadd7d
--- /dev/null
+++ b/cypress-tests/mitm-proxy/start_record.sh
@@ -0,0 +1,62 @@
+#!/usr/bin/env bash
+# Start mitmproxy in recording mode.
+#
+# Usage:
+# ./start.sh # default port 8888
+# PROXY_PORT=9090 ./start.sh
+
+set -euo pipefail
+
+PROXY_PORT="${PROXY_PORT:-8888}"
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+
+# ── Verify required tooling is installed ──────────────────────────────────
+for _tool in uv mitmdump; do
+ if ! command -v "${_tool}" >/dev/null 2>&1; then
+ echo "ERROR: required tool '${_tool}' not found on PATH." >&2
+ echo " Install uv (https://docs.astral.sh/uv/getting-started/installation/) and" >&2
+ echo " mitmproxy (https://docs.mitmproxy.org/stable/overview-installation/)." >&2
+ exit 1
+ fi
+done
+
+# ── Generate mitmproxy CA cert on first run ────────────────────────────────
+MITM_CERT_PATH="${HOME}/.mitmproxy/mitmproxy-ca-cert.pem"
+if [[ ! -f "${MITM_CERT_PATH}" ]]; then
+ echo "==> First run: generating mitmproxy CA cert..."
+ timeout 3 mitmdump --listen-port "${PROXY_PORT}" 2>/dev/null || true
+fi
+
+if [[ ! -f "${MITM_CERT_PATH}" ]]; then
+ echo "ERROR: could not generate mitmproxy CA cert at ${MITM_CERT_PATH}"
+ exit 1
+fi
+
+# Encode newlines as literal \r\n sequences — this is what Hyperswitch's
+# apply_mitm_certificate() expects (it does replace("\\r\\n", "\n") to decode)
+MITM_CERT=$(sed 's/$/\\r\\n/' "${MITM_CERT_PATH}" | tr -d '\n')
+
+# ── Print env vars BEFORE blocking on mitmproxy ───────────────────────────
+echo ""
+echo "Copy these exports into the Hyperswitch terminal, then start the router:"
+echo "──────────────────────────────────────────────────────────────────────"
+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 "cargo run --bin router"
+echo "──────────────────────────────────────────────────────────────────────"
+echo ""
+echo "==> Starting mitmproxy on :${PROXY_PORT} (Ctrl+C to stop)"
+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 " export CYPRESS_PROXY_ADMIN_URL=http://127.0.0.1:8001"
+echo ""
+
+# ── Run mitmproxy in the foreground so errors are visible ─────────────────
+exec uv run --with-requirements "${SCRIPT_DIR}/requirements.txt" \
+ mitmdump \
+ -s "${SCRIPT_DIR}/mitm_capture.py" \
+ --listen-port "${PROXY_PORT}"
diff --git a/cypress-tests/mitm-proxy/start_replay.sh b/cypress-tests/mitm-proxy/start_replay.sh
new file mode 100755
index 0000000000..9e6b72310a
--- /dev/null
+++ b/cypress-tests/mitm-proxy/start_replay.sh
@@ -0,0 +1,103 @@
+#!/usr/bin/env bash
+# Start mitmproxy in replay mode — serves cassettes instead of real connectors.
+#
+# Usage:
+# ./start_replay.sh # permissive: MISS forwards to live connector
+# ./start_replay.sh --strict # strict: MISS returns 599, never live
+# PROXY_PORT=9090 ./start_replay.sh
+#
+# Env overrides (also used by CI):
+# CAPTURE_DIR directory to load cassettes from (default: <script_dir>/captures)
+# ADMIN_PORT test-lifecycle admin port (default: 8001, read by mitm_replay.py)
+# REPLAY_STRICT set to 1 to enable strict mode (same as --strict flag)
+
+set -euo pipefail
+
+STRICT_FLAG=0
+for arg in "$@"; do
+ case "$arg" in
+ --strict) STRICT_FLAG=1 ;;
+ *) echo "WARN: unknown argument '${arg}' ignored" >&2 ;;
+ esac
+done
+
+if [[ "${STRICT_FLAG}" == "1" ]]; then
+ export REPLAY_STRICT=1
+fi
+STRICT_MODE="${REPLAY_STRICT:-0}"
+
+PROXY_PORT="${PROXY_PORT:-8888}"
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+CAPTURE_DIR="${CAPTURE_DIR:-${SCRIPT_DIR}/captures}"
+export CAPTURE_DIR
+
+# ── Verify required tooling is installed ──────────────────────────────────
+for _tool in uv mitmdump; do
+ if ! command -v "${_tool}" >/dev/null 2>&1; then
+ echo "ERROR: required tool '${_tool}' not found on PATH." >&2
+ echo " Install uv (https://docs.astral.sh/uv/getting-started/installation/) and" >&2
+ echo " mitmproxy (https://docs.mitmproxy.org/stable/overview-installation/)." >&2
+ exit 1
+ fi
+done
+
+if [[ -z "$(find "${CAPTURE_DIR}" -name '*.json' 2>/dev/null)" ]]; then
+ echo "ERROR: No cassettes found in ${CAPTURE_DIR}/. Record first (./start.sh) or set CAPTURE_DIR."
+ exit 1
+fi
+
+MITM_CERT_PATH="${HOME}/.mitmproxy/mitmproxy-ca-cert.pem"
+if [[ ! -f "${MITM_CERT_PATH}" ]]; then
+ echo "ERROR: mitmproxy CA cert not found at ${MITM_CERT_PATH}. Run mitmdump once to generate it."
+ exit 1
+fi
+
+# Local-dev hand-holding: only show when stdout is a terminal. CI runs this
+# non-interactively and already sets the router exports itself.
+if [[ -t 1 ]]; then
+ MITM_CERT=$(sed 's/$/\\r\\n/' "${MITM_CERT_PATH}" | tr -d '\n')
+
+ echo ""
+ echo "Copy these exports into the Hyperswitch terminal, then start the router:"
+ echo "──────────────────────────────────────────────────────────────────────"
+ 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_ENABLED=\"true\""
+ echo "export ROUTER__PROXY__MITM_CA_CERTIFICATE=\"${MITM_CERT}\""
+ echo "export ROUTER__TRACE_HEADER__ID_REUSE_STRATEGY=\"use_incoming\""
+ echo "cargo run --bin router"
+ echo "──────────────────────────────────────────────────────────────────────"
+ echo ""
+ if [[ "${STRICT_MODE}" == "1" ]]; then
+ MODE_DESC="STRICT — MISS / no-rid blocked with 599 (connector never called)"
+ else
+ MODE_DESC="permissive — MISS / no-rid forwarded to live connector"
+ fi
+
+ echo "==> Starting mitmproxy (replay mode) on :${PROXY_PORT} (Ctrl+C to stop)"
+ echo " Mode : ${MODE_DESC}"
+ echo " HIT = served from cassette"
+ echo " MISS = cassette not found"
+ echo " 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 " export CYPRESS_PROXY_ADMIN_URL=http://127.0.0.1:${ADMIN_PORT:-8001}"
+ echo ""
+fi
+
+# connection_strategy=lazy: never open an upstream connection on CONNECT.
+# With the default (eager), mitmproxy dials the real connector host the
+# instant the tunnel opens — to clone its TLS cert — before our replay
+# hook runs. In CI that host resolves but egress is blocked, so the dial
+# hangs until Hyperswitch's 30s client timeout fires → 502, cassette never
+# served. lazy defers the dial so HIT/strict-MISS are served immediately;
+# 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