diff --git a/docs/contributing/actions/testing/playwright.md b/docs/contributing/actions/testing/playwright.md index 12a7cb6601..3edc43f9c9 100644 --- a/docs/contributing/actions/testing/playwright.md +++ b/docs/contributing/actions/testing/playwright.md @@ -59,7 +59,7 @@ The propagation chain has four hops: 1. The host environment variable `INFINITO_PLAYWRIGHT_KEEP` (set on the host shell, by `act --env INFINITO_PLAYWRIGHT_KEEP=true`, or by the GitHub Actions repository variable forwarded into each `test-deploy-*.yml` workflow as `INFINITO_PLAYWRIGHT_KEEP: ${{ vars.INFINITO_PLAYWRIGHT_KEEP }}`). 2. `roles/test-e2e-playwright/defaults/main.yml` reads the host value into `test_e2e_playwright_keep` via `lookup('env', 'INFINITO_PLAYWRIGHT_KEEP')`. Inventory MAY override the role variable per environment in `group_vars` or `host_vars`. -3. `roles/test-e2e-playwright/tasks/02_run_one.yml` forwards the resolved value into the Playwright container as `-e INFINITO_PLAYWRIGHT_KEEP={{ test_e2e_playwright_keep }}`. +3. `roles/test-e2e-playwright/tasks/03_run_pass.yml` forwards the resolved value into the Playwright container as `-e INFINITO_PLAYWRIGHT_KEEP={{ test_e2e_playwright_keep }}`. 4. `roles/test-e2e-playwright/files/playwright.config.js` switches `trace`, `screenshot`, and `video` to `on` when the container value is `true`. It otherwise leaves the failure-only defaults (`retain-on-failure` for trace and video, `only-on-failure` for screenshot). Set the variable for the contexts you need: diff --git a/roles/test-e2e-playwright/AGENTS.md b/roles/test-e2e-playwright/AGENTS.md index 9ca71e96b4..b85f080f77 100644 --- a/roles/test-e2e-playwright/AGENTS.md +++ b/roles/test-e2e-playwright/AGENTS.md @@ -12,7 +12,7 @@ Changes here affect every application role that uses it. ## File-Specific Rules -### `tasks/02_run_one.yml` +### `tasks/02_run_one.yml` and `tasks/03_run_pass.yml` - You MUST NOT add new `set_fact` variables that shadow or wrap existing `TEST_E2E_PLAYWRIGHT_*` variables. - You MUST NOT read from role `vars/main.yml` mappings of consuming roles (e.g. `test_e2e_playwright.*`) to override runner behaviour. diff --git a/roles/test-e2e-playwright/README.md b/roles/test-e2e-playwright/README.md index d42483a4a4..093620029e 100644 --- a/roles/test-e2e-playwright/README.md +++ b/roles/test-e2e-playwright/README.md @@ -31,7 +31,8 @@ This role: - Optionally waits until the application responds with HTTP `200` or `302` - Injects CA trust automatically for `TLS_MODE=self_signed` (via `CA_TRUST.*`), so Playwright accepts self-signed cert chains - Runs Playwright in Docker with stable browser settings (`--ipc=host`, `--shm-size=1g`) -- Stores per-role reports/artifacts under `TEST_E2E_PLAYWRIGHT_REPORTS_BASE_DIR/` +- Runs the suite once per role on one network it is served on (`lookup('network_siblings', ...)`), picked at random when there are several and kept for the flake retry, with the `.env` rendered for that network's vhost +- Stores per-role reports/artifacts under `TEST_E2E_PLAYWRIGHT_REPORTS_BASE_DIR/`, or under `+` when the pick is not the canonical network ## Cosmos @@ -83,8 +84,9 @@ This role ships central Playwright defaults: - `templates/package.json.j2`: `@playwright/test` version derived from `meta/services.yml.playwright.version` - `files/playwright.config.js`: shared Playwright configuration +- `files/network-leak.spec.js`: guest persona and cross-network leak check, staged next to every role spec and skipped unless `PLAYWRIGHT_NETWORK_LEAK=true`, which the runner sets when the role is served on more than one network -Both are used as central defaults for every app role. +All three are used as central defaults for every app role. ## Variables diff --git a/roles/test-e2e-playwright/defaults/main.yml b/roles/test-e2e-playwright/defaults/main.yml index c8bd24efb5..a8e8615ac6 100644 --- a/roles/test-e2e-playwright/defaults/main.yml +++ b/roles/test-e2e-playwright/defaults/main.yml @@ -30,7 +30,7 @@ test_e2e_playwright_run_timeout: 3600 test_e2e_playwright_test_timeout: 300000 -# Front-proxy readiness probe (test-e2e-playwright/tasks/02_run_one.yml); role-overridable via each app's vars/main.yml. +# Front-proxy readiness probe (test-e2e-playwright/tasks/03_run_pass.yml); role-overridable via each app's vars/main.yml. test_e2e_playwright_wait_retries: 30 test_e2e_playwright_wait_delay: 5 diff --git a/roles/test-e2e-playwright/files/network-leak.spec.js b/roles/test-e2e-playwright/files/network-leak.spec.js new file mode 100644 index 0000000000..cea4b3cf1f --- /dev/null +++ b/roles/test-e2e-playwright/files/network-leak.spec.js @@ -0,0 +1,56 @@ +const { test, expect } = require("@playwright/test"); +const { gotoOnion, normalizeUrl, readEnv, runGuestFlow } = require("./personas"); +const { crossNetworkLeaks } = require("./personas/utils/network"); +const { resolveTimeout } = require("./timeouts"); + +const SETTLE_MS = 15_000; + +test.describe("network isolation", () => { + test.skip( + readEnv("PLAYWRIGHT_NETWORK_LEAK").toLowerCase() !== "true", + "the node serves this role on one network only", + ); + + test("guest stays signed out on this network", async ({ page }) => { + await runGuestFlow(page); + }); + + test("the page stays inside its network", async ({ page }) => { + const baseUrl = normalizeUrl(process.env.APP_BASE_URL); + test.skip(!baseUrl, "role has no public surface"); + test.setTimeout(resolveTimeout(120_000)); + + const requests = []; + const consoleErrors = []; + page.on("request", (request) => { + let documentUrl = baseUrl; + if (!request.isNavigationRequest()) { + try { + documentUrl = request.frame().url(); + } catch { + documentUrl = baseUrl; + } + } + requests.push({ url: request.url(), documentUrl }); + }); + page.on("console", (message) => { + if (message.type() === "error") consoleErrors.push(message.text()); + }); + + await page.context().clearCookies(); + await gotoOnion(page, baseUrl, { waitUntil: "domcontentloaded" }); + await page + .waitForLoadState("networkidle", { timeout: resolveTimeout(SETTLE_MS) }) + .catch((err) => { + if (err.name !== "TimeoutError") throw err; + }); + + const leaks = crossNetworkLeaks({ + requests, + consoleErrors, + suffixes: JSON.parse(readEnv("PLAYWRIGHT_NETWORK_SUFFIXES")), + allowedHosts: readEnv("PLAYWRIGHT_NETWORK_ALLOWED_HOSTS").split(",").filter(Boolean), + }); + expect(leaks, leaks.join("\n")).toEqual([]); + }); +}); diff --git a/roles/test-e2e-playwright/files/onion-test.js b/roles/test-e2e-playwright/files/onion-test.js index 0bdbc26192..43787e3d33 100644 --- a/roles/test-e2e-playwright/files/onion-test.js +++ b/roles/test-e2e-playwright/files/onion-test.js @@ -15,7 +15,12 @@ const isOnion = Object.values(process.env).some( const test = base.test.extend({ browser: async ({ playwright }, use) => { const proxy = process.env.PLAYWRIGHT_PROXY - ? { server: process.env.PLAYWRIGHT_PROXY } + ? { + server: process.env.PLAYWRIGHT_PROXY, + ...(process.env.PLAYWRIGHT_PROXY_BYPASS + ? { bypass: process.env.PLAYWRIGHT_PROXY_BYPASS } + : {}), + } : undefined; let browser; if (isOnion) { diff --git a/roles/test-e2e-playwright/files/personas/utils/env.js b/roles/test-e2e-playwright/files/personas/utils/env.js index 5e1c319d35..599672f971 100644 --- a/roles/test-e2e-playwright/files/personas/utils/env.js +++ b/roles/test-e2e-playwright/files/personas/utils/env.js @@ -7,7 +7,7 @@ const { test } = require("@playwright/test"); const { isServiceEnabled } = require("../../service-gating"); -const { resolveTimeout } = require("../../timeouts"); +const { isOnionTarget, resolveTimeout } = require("../../timeouts"); const { installCspHeaderRecorder } = require("./csp"); function decodeDotenvQuoted(value) { @@ -29,9 +29,9 @@ function readEnv(name) { return decodeDotenvQuoted(process.env[name] || ""); } -/** True when the role under test is served over a `.onion` (Tor) canonical domain. */ +/** True when the role under test is served over a `.onion` (Tor) domain. */ function isOnionCanonical() { - return /\.onion$/i.test(readEnv("CANONICAL_DOMAIN").trim()); + return isOnionTarget(); } /** diff --git a/roles/test-e2e-playwright/files/personas/utils/network.js b/roles/test-e2e-playwright/files/personas/utils/network.js new file mode 100644 index 0000000000..f3688e3222 --- /dev/null +++ b/roles/test-e2e-playwright/files/personas/utils/network.js @@ -0,0 +1,56 @@ +const CLEARNET = "clearnet"; + +function hostOf(url) { + try { + return new URL(url).hostname.toLowerCase().replace(/\.$/, ""); + } catch { + return ""; + } +} + +/** + * Args: + * host: a request or document host name. + * suffixes: network name -> host suffix, as the network registry declares it. + * + * Returns: + * The first network whose suffix the host carries, else "clearnet". + */ +function networkOf(host, suffixes) { + const name = String(host || "").toLowerCase().replace(/\.$/, ""); + for (const [network, suffix] of Object.entries(suffixes || {})) { + if (suffix && name.endsWith(suffix)) return network; + } + return CLEARNET; +} + +/** + * Args: + * requests: [{ url, documentUrl }] per request the page issued; documentUrl + * is the document the request was issued from. + * consoleErrors: the error texts the page logged to the console. + * suffixes: network name -> host suffix. + * allowedHosts: hosts every network may reach, i.e. the SSO issuer. + * + * Returns: + * One finding per request that leaves the network of its document and per + * mixed-content load the browser blocked. + */ +function crossNetworkLeaks({ requests, consoleErrors, suffixes, allowedHosts }) { + const allowed = new Set((allowedHosts || []).map((host) => host.toLowerCase())); + const findings = []; + for (const { url, documentUrl } of requests || []) { + const host = hostOf(url); + const origin = hostOf(documentUrl); + if (!host || !origin || allowed.has(host)) continue; + const from = networkOf(origin, suffixes); + const to = networkOf(host, suffixes); + if (from !== to) findings.push(`${from} document ${documentUrl} requested ${to} ${url}`); + } + for (const text of consoleErrors || []) { + if (/mixed content/i.test(text)) findings.push(`blocked mixed content: ${text}`); + } + return findings; +} + +module.exports = { networkOf, crossNetworkLeaks }; diff --git a/roles/test-e2e-playwright/files/playwright.config.js b/roles/test-e2e-playwright/files/playwright.config.js index 0587e22fcb..358aa7cb4b 100644 --- a/roles/test-e2e-playwright/files/playwright.config.js +++ b/roles/test-e2e-playwright/files/playwright.config.js @@ -22,6 +22,15 @@ function onionSecureOrigins() { const onionSecure = onionSecureOrigins(); +const proxy = process.env.PLAYWRIGHT_PROXY + ? { + server: process.env.PLAYWRIGHT_PROXY, + ...(process.env.PLAYWRIGHT_PROXY_BYPASS + ? { bypass: process.env.PLAYWRIGHT_PROXY_BYPASS } + : {}), + } + : undefined; + /** * The timeout the harness renders into the staged .env under this name. * @@ -65,7 +74,7 @@ module.exports = defineConfig({ // Route the browser through a SOCKS proxy when set (e.g. Tor for .onion // targets, which Chromium cannot resolve over normal DNS). Empty/unset = // direct connection (unchanged default for clearnet targets). - proxy: process.env.PLAYWRIGHT_PROXY ? { server: process.env.PLAYWRIGHT_PROXY } : undefined, + proxy, launchOptions: onionSecure.length ? { args: [`--unsafely-treat-insecure-origin-as-secure=${onionSecure.join(",")}`] } : undefined, diff --git a/roles/test-e2e-playwright/files/timeouts.js b/roles/test-e2e-playwright/files/timeouts.js index 24d4a39165..b4c768610a 100644 --- a/roles/test-e2e-playwright/files/timeouts.js +++ b/roles/test-e2e-playwright/files/timeouts.js @@ -5,15 +5,23 @@ * (Tor) service, by an extra multiplier — Tor circuits add per-request latency. */ -function _canonicalDomain() { - const raw = process.env.CANONICAL_DOMAIN || ""; +function _unquoted(name) { + const raw = process.env[name] || ""; const unquoted = raw.length >= 2 && raw.startsWith('"') && raw.endsWith('"') ? raw.slice(1, -1) : raw; return unquoted.trim(); } +function _targetHost() { + try { + return new URL(_unquoted("APP_BASE_URL")).hostname; + } catch { + return _unquoted("CANONICAL_DOMAIN"); + } +} + function isOnionTarget() { - return /\.onion$/i.test(_canonicalDomain()); + return /\.onion$/i.test(_targetHost()); } function isSplitRealmOidc() { diff --git a/roles/test-e2e-playwright/tasks/01_setup/orchestrate.yml b/roles/test-e2e-playwright/tasks/01_setup/orchestrate.yml index 9580f19f34..ad08f03cdd 100644 --- a/roles/test-e2e-playwright/tasks/01_setup/orchestrate.yml +++ b/roles/test-e2e-playwright/tasks/01_setup/orchestrate.yml @@ -14,6 +14,10 @@ - name: 🧰 Prepare shared @playwright/test install ansible.builtin.include_tasks: 01_setup.yml +- name: 🎲 Start the run without a network pick + ansible.builtin.set_fact: + _playwright_network_picks: {} + - name: ▶️ Run Playwright for each detected role ansible.builtin.include_tasks: 02_run_one.yml loop: "{{ TEST_E2E_PLAYWRIGHT_APPS }}" diff --git a/roles/test-e2e-playwright/tasks/02_run_one.yml b/roles/test-e2e-playwright/tasks/02_run_one.yml index 77513ff18e..386307d930 100644 --- a/roles/test-e2e-playwright/tasks/02_run_one.yml +++ b/roles/test-e2e-playwright/tasks/02_run_one.yml @@ -159,129 +159,23 @@ state: directory mode: "0755" -- name: 📄 Render .env from templates/playwright.env.j2 - ansible.builtin.copy: - dest: "{{ _playwright_stage_dir }}/.env" - mode: "0644" - content: | - {{ lookup('template', _playwright_env_template) }} - {% for name, value in TEST_E2E_PLAYWRIGHT_CONFIG_TIMEOUTS.items() %} - {{ name }}={{ value }} - {% endfor %} - vars: - application_id: "{{ application_id }}" - domains: "{{ lookup('domains') }}" - -- name: ⏳ Wait until application is ready (any non-error response) - uri_retry: - url: "{{ lookup('tls', application_id, 'url.base') }}" - status_code: "{{ range(100, 500) | list }}" - validate_certs: false - follow_redirects: none - register: _wait_result - retries: "{{ test_e2e_playwright_wait_retries }}" - delay: "{{ test_e2e_playwright_wait_delay }}" - until: >- - _wait_result.status is defined and - _wait_result.status | int >= 100 and - _wait_result.status | int < 500 - when: - - TEST_E2E_PLAYWRIGHT_WAIT_ENABLED | bool - - not (lookup('tls', application_id, 'url.base') is search('\.onion')) - - lookup('config', application_id, 'services.frontend.enabled', true) | bool - -- name: ✅ Ensure reports dir exists - ansible.builtin.file: - path: "{{ _playwright_reports_dir }}" - state: directory - mode: "0755" - - name: 📊 Collect host disk diagnostics before Playwright ansible.builtin.script: "{{ role_path }}/files/dump_disk_diagnostics.sh" changed_when: false when: MODE_DEBUG | bool -- name: ⏳ Wait until the onion answers over Tor (recreate circuits on exhaustion) - ansible.builtin.script: >- - {{ role_path }}/files/wait_onion_reachable.sh - {{ lookup('tor_socks') | quote }} - {{ lookup('domain', application_id) | quote }} - {{ TEST_E2E_PLAYWRIGHT_ONION_PROBE_RETRIES | int }} - {{ TEST_E2E_PLAYWRIGHT_ONION_PROBE_DELAY | int }} - {{ lookup('container', 'svc-net-tor', 'directories.instance') | quote }} - changed_when: false - become: true - when: TEST_E2E_PLAYWRIGHT_IS_ONION | bool - -- name: ▶️ Run Playwright container - ansible.builtin.command: - argv: >- - {{ - ['container', 'run', '--rm', '--ipc=host', '--shm-size=1g'] - + ( - ['--network', 'host'] - if DEPLOYMENT_MODE == 'swarm' - else ( - ['--add-host=host.docker.internal:host-gateway'] - + ( - ['--add-host=' ~ lookup('tls', 'web-app-keycloak', 'domain') ~ ':host-gateway'] - if 'web-app-keycloak' in group_names - else [] - ) - ) - ) - + ['--env-file', _playwright_stage_dir ~ '/.env'] - + ['-e', 'INFINITO_PLAYWRIGHT_KEEP=' ~ test_e2e_playwright_keep] - + ['-e', 'INFINITO_PLAYWRIGHT_GLOBAL_TIMEOUT_MS=' ~ TEST_E2E_PLAYWRIGHT_GLOBAL_TIMEOUT_MS] - + ['-e', 'PLAYWRIGHT_PROXY=' ~ TEST_E2E_PLAYWRIGHT_PROXY] - + ['-e', 'PLAYWRIGHT_WORKERS=' ~ test_e2e_playwright_workers] - + ['-e', 'PLAYWRIGHT_FULLY_PARALLEL=' ~ TEST_E2E_PLAYWRIGHT_FULLY_PARALLEL] - + ['-e', 'PLAYWRIGHT_TIMEOUT_FACTOR=' ~ TIMEOUT_FACTOR] - + (['-e', 'PLAYWRIGHT_ONION_TIMEOUT_MULTIPLIER=' ~ TEST_E2E_PLAYWRIGHT_ONION_TIMEOUT_MULTIPLIER] if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else []) - + ['-v', _playwright_stage_dir ~ ':/e2e'] - + ['-v', _playwright_stage_dir ~ '/volume:/volume'] - + ['-v', _playwright_reports_dir ~ ':/reports'] - + ['-v', TEST_E2E_PLAYWRIGHT_SHARED_NODE_MODULES ~ ':/e2e/node_modules:ro'] - + ['-v', TEST_E2E_PLAYWRIGHT_SHARED_PERSONAS ~ ':/e2e/tests/personas:ro'] - + ['-w', '/e2e'] - + [TEST_E2E_PLAYWRIGHT_IMAGE] - + ['/bin/bash', '-lc', TEST_E2E_PLAYWRIGHT_COMMAND] - }} - timeout: "{{ lookup('timeout', TEST_E2E_PLAYWRIGHT_RUN_TIMEOUT_EFFECTIVE) | int }}" - environment: >- - {{ - { - 'CA_TRUST_CERT_HOST': _playwright_ca_cert_host, - 'CA_TRUST_WRAPPER_HOST': _playwright_ca_wrapper_host, - 'CA_TRUST_NAME': _playwright_ca_trust_name - } if (_playwright_ca_required | bool) else {} - }} - register: _playwright_run - changed_when: false - failed_when: false - -- name: 💬 Print Playwright output (on failure) - ansible.builtin.debug: - msg: | - rc: {{ _playwright_run.rc | default('') }} - - stdout: - {{ _playwright_run.stdout | default('') }} - - stderr: - {{ _playwright_run.stderr | default(_playwright_run.msg | default('')) }} - when: (_playwright_run.rc | default(1)) != 0 - changed_when: false - -- name: 📝 Record failure +- name: 🎲 Pick the network this role is tested on ansible.builtin.set_fact: - _playwright_failures: "{{ (_playwright_failures | default([])) + [application_id] }}" - when: (_playwright_run.rc | default(1)) != 0 + _playwright_network_picks: >- + {{ _playwright_network_picks + | combine({application_id: lookup('network_siblings', lookup('domain', application_id)) | random}) }} + when: application_id not in _playwright_network_picks -- name: 🗄️ Archive Playwright reports for this variant + pass - ansible.builtin.script: >- - {{ role_path }}/files/archive_playwright_reports.sh - {{ _playwright_reports_dir | quote }} - {{ VARIANT_INDEX | int }} - {{ ASYNC_ENABLED | bool | string | lower }} - changed_when: true +- name: 🌈 Run Playwright on the picked network + ansible.builtin.include_tasks: 03_run_pass.yml + vars: + _playwright_passes: "{{ lookup('network_siblings', lookup('domain', application_id)) }}" + _playwright_pass_domain: "{{ _playwright_network_picks[application_id] }}" + _playwright_pass_reports_dir: >- + {{ _playwright_reports_dir if _playwright_pass_domain == _playwright_passes[0] + else _playwright_reports_dir ~ '+' ~ (_playwright_pass_domain | network_of) }} diff --git a/roles/test-e2e-playwright/tasks/03_run_pass.yml b/roles/test-e2e-playwright/tasks/03_run_pass.yml new file mode 100644 index 0000000000..7e5e429d2d --- /dev/null +++ b/roles/test-e2e-playwright/tasks/03_run_pass.yml @@ -0,0 +1,139 @@ +--- +- name: ✅ Ensure the pass reports dir exists + ansible.builtin.file: + path: "{{ _playwright_pass_reports_dir }}" + state: directory + mode: "0755" + +- name: 📄 Render .env from templates/playwright.env.j2 + ansible.builtin.copy: + dest: "{{ _playwright_stage_dir }}/.env" + mode: "0644" + content: | + {% set _env = lookup('template', _playwright_env_template, template_vars={'domain': _playwright_pass_domain}) %} + {% if _playwright_pass_domain == _playwright_passes[0] %} + {{ _env }} + {% else %} + {% for line in _env.splitlines() %} + {{ line if not line.startswith('CANONICAL_DOMAIN=') + else 'CANONICAL_DOMAIN=' ~ (lookup('network_siblings', line.split('=', 1)[1] | replace('"', '')) + | in_network(_playwright_pass_domain | network_of) | first | dotenv_quote) }} + {% endfor %} + {% endif %} + {% for name, value in TEST_E2E_PLAYWRIGHT_CONFIG_TIMEOUTS.items() %} + {{ name }}={{ value }} + {% endfor %} + PLAYWRIGHT_NETWORK_LEAK={{ (_playwright_passes | length > 1) | string | lower }} + PLAYWRIGHT_NETWORK_SUFFIXES={{ _playwright_passes | map('network_of') | network_suffixes | to_json }} + PLAYWRIGHT_NETWORK_ALLOWED_HOSTS={{ OIDC.URL | urlsplit('hostname') }} + vars: + application_id: "{{ application_id }}" + domains: "{{ lookup('domains') }}" + +- name: ⏳ Wait until application is ready (any non-error response) + uri_retry: + url: "{{ lookup('tls', _playwright_pass_domain, 'url.base') }}" + status_code: "{{ range(100, 500) | list }}" + validate_certs: false + follow_redirects: none + register: _wait_result + retries: "{{ test_e2e_playwright_wait_retries }}" + delay: "{{ test_e2e_playwright_wait_delay }}" + until: >- + _wait_result.status is defined and + _wait_result.status | int >= 100 and + _wait_result.status | int < 500 + when: + - TEST_E2E_PLAYWRIGHT_WAIT_ENABLED | bool + - not (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) + - lookup('config', application_id, 'services.frontend.enabled', true) | bool + +- name: ⏳ Wait until the onion answers over Tor (recreate circuits on exhaustion) + ansible.builtin.script: >- + {{ role_path }}/files/wait_onion_reachable.sh + {{ lookup('tor_socks') | quote }} + {{ _playwright_pass_domain | quote }} + {{ TEST_E2E_PLAYWRIGHT_ONION_PROBE_RETRIES | int }} + {{ TEST_E2E_PLAYWRIGHT_ONION_PROBE_DELAY | int }} + {{ lookup('container', 'svc-net-tor', 'directories.instance') | quote }} + changed_when: false + become: true + when: TEST_E2E_PLAYWRIGHT_IS_ONION | bool + +- name: ▶️ Run Playwright container + ansible.builtin.command: + argv: >- + {{ + ['container', 'run', '--rm', '--ipc=host', '--shm-size=1g'] + + ( + ['--network', 'host'] + if DEPLOYMENT_MODE == 'swarm' + else ( + ['--add-host=host.docker.internal:host-gateway'] + + ( + ['--add-host=' ~ lookup('tls', 'web-app-keycloak', 'domain') ~ ':host-gateway'] + if 'web-app-keycloak' in group_names + else [] + ) + ) + ) + + ['--env-file', _playwright_stage_dir ~ '/.env'] + + ['-e', 'INFINITO_PLAYWRIGHT_KEEP=' ~ test_e2e_playwright_keep] + + ['-e', 'INFINITO_PLAYWRIGHT_GLOBAL_TIMEOUT_MS=' ~ TEST_E2E_PLAYWRIGHT_GLOBAL_TIMEOUT_MS] + + ['-e', 'PLAYWRIGHT_PROXY=' ~ TEST_E2E_PLAYWRIGHT_PROXY] + + ( + ['-e', 'PLAYWRIGHT_PROXY_BYPASS=' ~ (OIDC.URL | urlsplit('hostname'))] + if (OIDC.URL | urlsplit('hostname') | network_of) != (_playwright_pass_domain | network_of) + else [] + ) + + ['-e', 'PLAYWRIGHT_WORKERS=' ~ test_e2e_playwright_workers] + + ['-e', 'PLAYWRIGHT_FULLY_PARALLEL=' ~ TEST_E2E_PLAYWRIGHT_FULLY_PARALLEL] + + ['-e', 'PLAYWRIGHT_TIMEOUT_FACTOR=' ~ TIMEOUT_FACTOR] + + (['-e', 'PLAYWRIGHT_ONION_TIMEOUT_MULTIPLIER=' ~ TEST_E2E_PLAYWRIGHT_ONION_TIMEOUT_MULTIPLIER] if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else []) + + ['-v', _playwright_stage_dir ~ ':/e2e'] + + ['-v', _playwright_stage_dir ~ '/volume:/volume'] + + ['-v', _playwright_pass_reports_dir ~ ':/reports'] + + ['-v', TEST_E2E_PLAYWRIGHT_SHARED_NODE_MODULES ~ ':/e2e/node_modules:ro'] + + ['-v', TEST_E2E_PLAYWRIGHT_SHARED_PERSONAS ~ ':/e2e/tests/personas:ro'] + + ['-w', '/e2e'] + + [TEST_E2E_PLAYWRIGHT_IMAGE] + + ['/bin/bash', '-lc', TEST_E2E_PLAYWRIGHT_COMMAND] + }} + timeout: "{{ lookup('timeout', TEST_E2E_PLAYWRIGHT_RUN_TIMEOUT_EFFECTIVE) | int }}" + environment: >- + {{ + { + 'CA_TRUST_CERT_HOST': _playwright_ca_cert_host, + 'CA_TRUST_WRAPPER_HOST': _playwright_ca_wrapper_host, + 'CA_TRUST_NAME': _playwright_ca_trust_name + } if (_playwright_ca_required | bool) else {} + }} + register: _playwright_run + changed_when: false + failed_when: false + +- name: 💬 Print Playwright output (on failure) + ansible.builtin.debug: + msg: | + rc: {{ _playwright_run.rc | default('') }} + + stdout: + {{ _playwright_run.stdout | default('') }} + + stderr: + {{ _playwright_run.stderr | default(_playwright_run.msg | default('')) }} + when: (_playwright_run.rc | default(1)) != 0 + changed_when: false + +- name: 📝 Record failure + ansible.builtin.set_fact: + _playwright_failures: "{{ (_playwright_failures | default([])) + [application_id] }}" + when: (_playwright_run.rc | default(1)) != 0 + +- name: 🗄️ Archive Playwright reports for this variant + pass + ansible.builtin.script: >- + {{ role_path }}/files/archive_playwright_reports.sh + {{ _playwright_pass_reports_dir | quote }} + {{ VARIANT_INDEX | int }} + {{ ASYNC_ENABLED | bool | string | lower }} + changed_when: true diff --git a/roles/test-e2e-playwright/vars/main.yml b/roles/test-e2e-playwright/vars/main.yml index e9aa5ae69b..d929180502 100644 --- a/roles/test-e2e-playwright/vars/main.yml +++ b/roles/test-e2e-playwright/vars/main.yml @@ -26,7 +26,7 @@ TEST_E2E_PLAYWRIGHT_SHARED_PERSONAS: "{{ TEST_E2E_PLAYWRIGHT_SHARED_DIR }}/perso TEST_E2E_PLAYWRIGHT_PERSONAS_ARCHIVE: "/tmp/infinito-playwright-personas.tar" TEST_E2E_PLAYWRIGHT_SHARED_STAMP: "{{ TEST_E2E_PLAYWRIGHT_SHARED_DIR }}/.installed-version" -TEST_E2E_PLAYWRIGHT_IS_ONION: "{{ lookup('tls', application_id, 'url.base') is search('\\.onion') }}" +TEST_E2E_PLAYWRIGHT_IS_ONION: "{{ (_playwright_pass_domain | network_of) == 'tor' }}" TEST_E2E_PLAYWRIGHT_PROXY: "{{ ('socks5://' ~ lookup('tor_socks', '127.0.0.1' if DEPLOYMENT_MODE == 'swarm' else 'host.docker.internal')) if (TEST_E2E_PLAYWRIGHT_IS_ONION | bool) else '' }}" diff --git a/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/network.test.js b/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/network.test.js new file mode 100644 index 0000000000..1322aa3264 --- /dev/null +++ b/tests/unit/javascript/roles/test-e2e-playwright/files/personas/utils/network.test.js @@ -0,0 +1,81 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const path = require("node:path"); + +const PROJECT_ROOT = path.resolve(__dirname, "../../../../../../../.."); +const { networkOf, crossNetworkLeaks } = require( + path.join(PROJECT_ROOT, "roles/test-e2e-playwright/files/personas/utils/network.js"), +); +const { DOMAIN } = require(path.join(PROJECT_ROOT, "tests/unit/javascript/utils/domain.js")); + +const SUFFIXES = { tor: ".onion" }; +const NODE = "b5abfs7uwr23x6vbjxqjatyscpmkm6qkmkla7eyapdi4zpwtrz6o4nqd.onion"; +const CLEARNET_PAGE = `https://wazuh.${DOMAIN}/app/wz-home`; +const ONION_PAGE = `http://wazuh.${NODE}/app/wz-home`; +const ISSUER = `auth.${DOMAIN}`; +const CSS = `https://css.${DOMAIN}/global.css`; +const CDN_JS = `https://cdn.${DOMAIN}/app.js`; + +test("a host is classified by the registry suffixes", () => { + assert.equal(networkOf(`cdn.${NODE}`, SUFFIXES), "tor"); + assert.equal(networkOf(`cdn.${DOMAIN}`, SUFFIXES), "clearnet"); + assert.equal(networkOf(`CDN.${NODE.toUpperCase()}.`, SUFFIXES), "tor"); +}); + +test("the wazuh regression of fork run 35925283225 is reported", () => { + const leaks = crossNetworkLeaks({ + requests: [ + { url: `http://cdn.${NODE}/_shared/fonts/inter.css`, documentUrl: CLEARNET_PAGE }, + { url: `http://matomo.${NODE}/matomo.js`, documentUrl: CLEARNET_PAGE }, + ], + consoleErrors: [ + `Mixed Content: The page at '${CLEARNET_PAGE}' was loaded over HTTPS, but ` + + `requested an insecure script 'http://matomo.${NODE}/matomo.js'. This ` + + "request has been blocked; the content must be served over HTTPS.", + ], + suffixes: SUFFIXES, + allowedHosts: [ISSUER], + }); + assert.equal(leaks.length, 3); + assert.match(leaks[0], /clearnet document .* requested tor http:\/\/cdn\./); + assert.match(leaks[2], /^blocked mixed content: /); +}); + +test("an onion document reaching a clearnet provider is reported", () => { + const leaks = crossNetworkLeaks({ + requests: [{ url: CSS, documentUrl: ONION_PAGE }], + consoleErrors: [], + suffixes: SUFFIXES, + allowedHosts: [ISSUER], + }); + assert.deepEqual(leaks, [ + `tor document ${ONION_PAGE} requested clearnet ${CSS}`, + ]); +}); + +test("the SSO issuer is reachable from every network", () => { + const leaks = crossNetworkLeaks({ + requests: [ + { url: `https://${ISSUER}/realms/${DOMAIN}/protocol/openid-connect/auth`, documentUrl: ONION_PAGE }, + ], + consoleErrors: [], + suffixes: SUFFIXES, + allowedHosts: [ISSUER], + }); + assert.deepEqual(leaks, []); +}); + +test("requests inside the document network pass", () => { + const leaks = crossNetworkLeaks({ + requests: [ + { url: `http://cdn.${NODE}/app.js`, documentUrl: ONION_PAGE }, + { url: CDN_JS, documentUrl: CLEARNET_PAGE }, + { url: "data:image/png;base64,AAAA", documentUrl: CLEARNET_PAGE }, + { url: CDN_JS, documentUrl: "about:blank" }, + ], + consoleErrors: ["TypeError: x is undefined"], + suffixes: SUFFIXES, + allowedHosts: [ISSUER], + }); + assert.deepEqual(leaks, []); +}); diff --git a/tests/unit/javascript/utils/domain.js b/tests/unit/javascript/utils/domain.js new file mode 100644 index 0000000000..ed7a295e6b --- /dev/null +++ b/tests/unit/javascript/utils/domain.js @@ -0,0 +1,20 @@ +const fs = require("node:fs"); +const path = require("node:path"); + +const PROJECT_ROOT = path.resolve(__dirname, "../../../.."); +const KEY = "INFINITO_DOMAIN="; + +/** + * Returns: + * The INFINITO_DOMAIN value declared in default.env. + */ +function defaultDomainPrimary() { + const line = fs + .readFileSync(path.join(PROJECT_ROOT, "default.env"), "utf8") + .split("\n") + .find((entry) => entry.startsWith(KEY)); + if (!line) throw new Error(`default.env declares no ${KEY.slice(0, -1)}`); + return line.slice(KEY.length).trim().replace(/^["']|["']$/g, ""); +} + +module.exports = { DOMAIN: defaultDomainPrimary() }; diff --git a/tests/unit/python/roles/test-e2e-playwright/test_env_canonical_domain.py b/tests/unit/python/roles/test-e2e-playwright/test_env_canonical_domain.py new file mode 100644 index 0000000000..c24a105fbb --- /dev/null +++ b/tests/unit/python/roles/test-e2e-playwright/test_env_canonical_domain.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import json +import unittest +from urllib.parse import urlsplit + +from jinja2 import Environment, StrictUndefined + +from plugins.filter.dotenv import dotenv_quote +from plugins.filter.network_of import in_network, network_of, network_suffixes +from plugins.lookup.network_siblings import served_siblings +from utils.cache.yaml import load_yaml_any +from utils.domains.default_primary import default_domain_primary + +from . import PROJECT_ROOT + +TASKS = PROJECT_ROOT / "roles/test-e2e-playwright/tasks/03_run_pass.yml" +TASK_NAME = "📄 Render .env from templates/playwright.env.j2" +PRIMARY = default_domain_primary() +NODE = "abcdefghijklmnopqrstuvwxyz234567abcdefghijklmnopqrstuvw.onion" +CLEARNET = [f"api.s3.{PRIMARY}", f"console.s3.{PRIMARY}"] +TOR = [f"api.s3.{NODE}", f"console.s3.{NODE}"] + + +def render(pass_domain: str) -> str: + tasks = load_yaml_any(str(TASKS)) + task = next(t for t in tasks if t.get("name") == TASK_NAME) + env = Environment(autoescape=False, trim_blocks=True, undefined=StrictUndefined) # noqa: S701 - dotenv file, not markup + env.filters.update( + dotenv_quote=dotenv_quote, + in_network=in_network, + network_of=network_of, + network_suffixes=network_suffixes, + to_json=json.dumps, + urlsplit=lambda url, part: getattr(urlsplit(url), part), + ) + + def lookup(name, term, template_vars=None): + if name == "template": + return ( + f'APP_BASE_URL="https://{template_vars["domain"]}/"\n' + f'CANONICAL_DOMAIN="{CLEARNET[1]}"\n' + ) + return served_siblings(term, {"web-app-minio": CLEARNET + TOR}, PRIMARY, NODE) + + return env.from_string(task["ansible.builtin.copy"]["content"]).render( + lookup=lookup, + _playwright_env_template="playwright.env.j2", + _playwright_pass_domain=pass_domain, + _playwright_passes=[CLEARNET[0], TOR[0]], + TEST_E2E_PLAYWRIGHT_CONFIG_TIMEOUTS={}, + OIDC={"URL": f"https://auth.{PRIMARY}/realms/main"}, + DEPLOYMENT_MODE="compose", + ) + + +class TestEnvCanonicalDomain(unittest.TestCase): + def test_onion_pick_moves_the_canonical_domain_to_its_onion_sibling(self): + rendered = render(TOR[0]) + self.assertIn(f'APP_BASE_URL="https://{TOR[0]}/"\n', rendered) + self.assertIn(f'CANONICAL_DOMAIN="{TOR[1]}"\n', rendered) + + def test_canonical_network_pick_keeps_the_rendered_env(self): + self.assertTrue( + render(CLEARNET[0]).startswith( + f'APP_BASE_URL="https://{CLEARNET[0]}/"\n' + f'CANONICAL_DOMAIN="{CLEARNET[1]}"\n' + ) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py index 4fb7076704..cb1d144b3d 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_readiness_until.py @@ -8,7 +8,7 @@ from utils.cache.yaml import load_yaml_any from . import PROJECT_ROOT -TASKS = PROJECT_ROOT / "roles/test-e2e-playwright/tasks/02_run_one.yml" +TASKS = PROJECT_ROOT / "roles/test-e2e-playwright/tasks/03_run_pass.yml" TASK_NAME = "⏳ Wait until application is ready (any non-error response)" diff --git a/tests/unit/python/roles/test-e2e-playwright/test_timeouts_helper.py b/tests/unit/python/roles/test-e2e-playwright/test_timeouts_helper.py index daed87f110..879b7babd7 100644 --- a/tests/unit/python/roles/test-e2e-playwright/test_timeouts_helper.py +++ b/tests/unit/python/roles/test-e2e-playwright/test_timeouts_helper.py @@ -13,11 +13,14 @@ import textwrap import unittest from pathlib import Path +from utils.domains.default_primary import default_domain_primary + from . import PROJECT_ROOT HELPER_PATH = str( PROJECT_ROOT / "roles" / "test-e2e-playwright" / "files" / "timeouts.js" ) +DOMAIN = default_domain_primary() def _have_node(): @@ -60,7 +63,7 @@ class TestTimeoutsHelper(unittest.TestCase): def test_clearnet_default_factor_is_identity(self): out = self._run( "t.resolveTimeout(60000)", - {"CANONICAL_DOMAIN": '"x.infinito.test"'}, + {"CANONICAL_DOMAIN": f'"x.{DOMAIN}"'}, ) self.assertIn("RESULT:60000", out) @@ -75,7 +78,7 @@ class TestTimeoutsHelper(unittest.TestCase): out = self._run( "t.resolveTimeout(60000)", { - "CANONICAL_DOMAIN": "x.infinito.test", + "CANONICAL_DOMAIN": f"x.{DOMAIN}", "PLAYWRIGHT_TIMEOUT_FACTOR": "2", }, ) @@ -96,7 +99,7 @@ class TestTimeoutsHelper(unittest.TestCase): out = self._run( "t.resolveTimeout(60000)", { - "CANONICAL_DOMAIN": "x.infinito.test", + "CANONICAL_DOMAIN": f"x.{DOMAIN}", "PLAYWRIGHT_TIMEOUT_FACTOR": "0", }, ) @@ -113,7 +116,23 @@ class TestTimeoutsHelper(unittest.TestCase): ) self.assertIn( "RESULT:false", - self._run("t.isOnionTarget()", {"CANONICAL_DOMAIN": '"x.infinito.test"'}), + self._run("t.isOnionTarget()", {"CANONICAL_DOMAIN": f'"x.{DOMAIN}"'}), + ) + + def test_is_onion_target_reads_app_base_url_first(self): + self.assertIn( + "RESULT:true", + self._run("t.isOnionTarget()", {"APP_BASE_URL": '"https://x.abc.onion/"'}), + ) + self.assertIn( + "RESULT:false", + self._run( + "t.isOnionTarget()", + { + "APP_BASE_URL": f'"https://x.{DOMAIN}/"', + "CANONICAL_DOMAIN": '"x.abc.onion"', + }, + ), )