diff --git a/.oxlintrc.json b/.oxlintrc.json index 0e96b7d..191996a 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -176,6 +176,101 @@ ] } }, + { + "files": ["e2e/**"], + "rules": { + "eslint/no-restricted-imports": [ + "error", + { + "paths": [ + { + "name": "@playwright/test", + "allowTypeImports": true, + "message": "Only e2e/support.ts imports values from Playwright, so that every journey gets the shared fixture and its contexts (ADR 0015). Import types only, and take test, expect, and the helpers from ./support.js." + }, + { + "name": "playwright", + "allowTypeImports": true, + "message": "Only e2e/support.ts imports values from Playwright, so that every journey gets the shared fixture and its contexts (ADR 0015). Import types only, and take test, expect, and the helpers from ./support.js." + }, + { + "name": "playwright/test", + "allowTypeImports": true, + "message": "Only e2e/support.ts imports values from Playwright, so that every journey gets the shared fixture and its contexts (ADR 0015). Import types only, and take test, expect, and the helpers from ./support.js." + }, + { + "name": "playwright-core", + "allowTypeImports": true, + "message": "Only e2e/support.ts imports values from Playwright, so that every journey gets the shared fixture and its contexts (ADR 0015). Import types only, and take test, expect, and the helpers from ./support.js." + } + ], + "patterns": [ + { + "regex": "(^|/)generated(/|$)", + "message": "Only the facade packages/api-client/src/index.ts imports the generated client." + }, + { + "regex": "^telemetry-web-api-client/", + "message": "Import the package root telemetry-web-api-client only." + } + ] + } + ], + "eslint/no-restricted-properties": [ + "error", + { + "property": "newContext", + "message": "Open browser contexts and pages through the helpers of e2e/support.ts, so that the Firefox workaround applies (ADR 0015)." + }, + { + "property": "launch", + "message": "Open browser contexts and pages through the helpers of e2e/support.ts, so that the Firefox workaround applies (ADR 0015)." + }, + { + "property": "launchPersistentContext", + "message": "Open browser contexts and pages through the helpers of e2e/support.ts, so that the Firefox workaround applies (ADR 0015)." + }, + { + "property": "launchServer", + "message": "Open browser contexts and pages through the helpers of e2e/support.ts, so that the Firefox workaround applies (ADR 0015)." + }, + { + "property": "connect", + "message": "Open browser contexts and pages through the helpers of e2e/support.ts, so that the Firefox workaround applies (ADR 0015)." + }, + { + "property": "connectOverCDP", + "message": "Open browser contexts and pages through the helpers of e2e/support.ts, so that the Firefox workaround applies (ADR 0015)." + }, + { + "object": "browser", + "property": "newPage", + "message": "Open browser contexts and pages through the helpers of e2e/support.ts, so that the Firefox workaround applies (ADR 0015)." + } + ] + } + }, + { + "files": ["e2e/support.ts", "e2e/playwright.config.ts"], + "rules": { + "eslint/no-restricted-imports": [ + "error", + { + "patterns": [ + { + "regex": "(^|/)generated(/|$)", + "message": "Only the facade packages/api-client/src/index.ts imports the generated client." + }, + { + "regex": "^telemetry-web-api-client/", + "message": "Import the package root telemetry-web-api-client only." + } + ] + } + ], + "eslint/no-restricted-properties": "off" + } + }, { "files": ["packages/api-client/src/index.ts"], "rules": { diff --git a/STACK.md b/STACK.md index 6f0363b..1acfd25 100644 --- a/STACK.md +++ b/STACK.md @@ -434,7 +434,7 @@ at the pin. | @tanstack/react-query | 5.108.4 | `telemetry-web-spa` | Server state and cache | MIT | | zod | 4.6.7 | `telemetry-web-api-client` | Executed validation of responses and problem bodies | MIT | | @hey-api/openapi-ts | 0.99.0 | `telemetry-web-api-client` (dev) | Generation of the SDK, types, and Zod schemas | MIT | -| @playwright/test | 1.65.1 | root, `telemetry-web-e2e` | Browser journeys | Apache-2.0 | +| @playwright/test | 1.65.1 | root, `telemetry-web-e2e` | Browser journeys; ships Chromium build 1255, Firefox 159.0 build 1572, and WebKit build 2388 (`browsers.json` of `playwright-core`) | Apache-2.0 | | @axe-core/playwright | 4.14.1 | `telemetry-web-e2e` | Accessibility checks in the journeys | MPL-2.0 (test only; the image holds no file of it) | | @types/react, @types/react-dom, @types/node | 19.3.3, 19.3.0, 24.19.4 | dev | Types; `@types/node` follows the Node 24 runtime | MIT | @@ -589,6 +589,7 @@ approval. | §1: `exactOptionalPropertyTypes` off for `packages/api-client/src/generated/` | The copied client runtime of Hey API is not checked with that one flag. | Nothing edits the directory; `contract-check`; every other strict flag stays on; the facade and the SPA keep the flag and read the generated code only as declarations. | ADR 0010 | A Hey API release whose runtime passes the flag. | | §3: no scan of the web builder images `node:-trixie-slim` and `rust:-slim-trixie` | A vulnerability in Node, npm, pnpm, or a builder Debian package that changes the SPA files or the server binary is not found by a scanner. | The tags equal the pins of `mise.toml` and `rust-toolchain.toml` (`crates/server/tests/deployment.rs`); `deps` prints the newest tags; `pnpm audit` and the source scan cover the npm packages of the build; `vuln` allows only the binary and `web/dist` out of the builder stages; `image-check` runs the built image; manual KEV comparison. | ADR 0010 | A scanner of the built image in CI; a builder-stage advisory in CISA KEV; a change of a builder image. | | §14: build and test of the web image before merge | The Railway build, settings, and healthcheck of `telemetry-web` are unverified before the merge. | A green `image-check` job of the PR head (`image-check-web.sh`); the post-release checks and the recovery of `docs/web-release.md`. | ADR 0008, ADR 0010 | Railway documents its Dockerfile build, or the Railway builder can run before the merge. | +| §3, §14: Firefox journeys of `e2e/` hide `ariaLabelledByElements` | In the project `firefox`, `e2e/support.ts` deletes the property from `Element.prototype` in the main world, because Firefox build 1572 crashes when two worlds read it (Mozilla bug 2090055). axe in Firefox does not check a reference that a script sets only through the property. Chromium and WebKit are unchanged. | `e2e/firefox-aria-reflection.spec.ts`: the regression test, the axe challenge test, the context test of `newBrowserContext`, the axe equivalence test in Chromium and WebKit, the source check of `web/src` and `packages/api-client/src`, and the removal guard. Each slice that adds a page or a state with an axe check adds the page or state to the equivalence test. The lint rules for `e2e/**` keep the fixture in front of every page: only `e2e/support.ts` and `e2e/playwright.config.ts` import values from Playwright, and only `e2e/support.ts` opens a context; ADR 0015 lists their known limits. | ADR 0015 | A stable Playwright release with Firefox build 1575 or later is older than 1440 minutes, or by 2027-02-28. The removal guard fails when the pinned Playwright ships such a build. | | Web profile §15: one image for server and SPA | The ingest service is a second image (Tesla's upstream server). | The application still ships as one image. | ADR 0009 | Permanent while the upstream server is used. | --- diff --git a/docs/adr/0015-firefox-aria-reflection-workaround.md b/docs/adr/0015-firefox-aria-reflection-workaround.md new file mode 100644 index 0000000..17ce67a --- /dev/null +++ b/docs/adr/0015-firefox-aria-reflection-workaround.md @@ -0,0 +1,189 @@ +# ADR 0015: Firefox ARIA reflection workaround in the browser journeys + +- Status: Accepted, 28 November 2026. A scoped exception under + `DOCTRINE.md` "Exceptions". Decided by the lead within delegated + authority, with approval by an independent reviewer (qa-enforcer) in PR + #51: , + with the conditions of the addendum + , + and kept for the extended evidence in the delta review + + on the condition of the corrected limits below. +- Responsible lead: the lead agent of the delivery task. +- Scope: the Playwright journeys of `e2e/` in the project `firefox` only, + with Playwright 1.65.1 and its Firefox 159.0, build 1572. The workaround + does not change the application, the release image, or the journeys in + Chromium and WebKit. + +## Context + +- The Firefox of Playwright 1.65.1 (Firefox 159.0, build 1572) crashes its + content process (SIGSEGV in + `Element::GetAttrAssociatedElementsForBindings`) when two JavaScript + worlds read `ariaLabelledByElements` of one element: + - Playwright's utility world reads the property in the accessible name + computation of a role query with a name, of `ariaSnapshot()`, and of a + polling `expect`. + - The page's main world reads the property in axe-core 4.14.1 (rule data + `prop: 'ariaLabelledByElements'`, function `getIdrefsValue`) and in + `page.evaluate`. +- Playwright then reports "Page crashed". A minimal page reproduces the + crash without the application: + `

x

`, a + `getByRole('region', { name: 'x' })` query, then a main-world read of + the property. +- The crash is not specific to macOS. CI on linux/amd64 crashed six + Firefox journeys of the battery-view slice: + . +- Upstream records: + - Mozilla bug 2090055 (RESOLVED FIXED, Firefox 163): + . + - Playwright issues 43967 and 44135 (closed): + , + . + - Playwright PR 43982 rolls Firefox to build 1575 (merged): + . + - axe-core issue 5549 (open): + . +- On 28 November 2026, the npm tag `latest` of `@playwright/test` is + 1.65.1. The tag `next` is 1.66.0-alpha. No stable release ships Firefox + build 1575 or later. +- The Playwright 1.65.1 utility world reads only `ariaLabelledByElements` + of the eight ARIA element-reflection properties of WAI-ARIA 1.3 + (`ariaActiveDescendantElement`, `ariaControlsElements`, + `ariaDescribedByElements`, `ariaDetailsElements`, + `ariaErrorMessageElements`, `ariaFlowToElements`, + `ariaLabelledByElements`, `ariaOwnsElements`). A reproduction with each + property, a role query, a description query, an error message query, + an `ariaSnapshot()`, and a main-world read crashed only for + `ariaLabelledByElements`. The crash of the other seven properties is + not reachable from the utility world of Playwright 1.65.1. +- The same reproduction with the Firefox build 1584 (Firefox 160.0), + driven by Playwright 1.65.1 on macOS arm64, did not crash. Build 1575 + was not tested. +- The application on `main` passes the Firefox journeys without the + workaround. The crash comes when a journey queries a name and then runs + axe on an element with `aria-labelledby`. + +## Decision + +1. In the Playwright project `firefox` only, the shared fixture of + `e2e/support.ts` adds an init script to each browser context. The init + script deletes `ariaLabelledByElements` from `Element.prototype` in the + main world, before any page script runs. axe-core then reads + `aria-labelledby` from the content attribute. The list of deleted + properties is `HIDDEN_ARIA_REFLECTION_PROPERTIES` in `e2e/support.ts`. +2. `e2e/support.ts` is the only e2e file that imports values from + `@playwright/test`, `playwright`, `playwright/test`, or + `playwright-core`. Every other file under `e2e/` imports types only + from these modules, and takes `test`, `expect`, and the helpers from + `e2e/support.ts`. The lint rule `no-restricted-imports` for `e2e/**` in + `.oxlintrc.json` enforces this, also for a default import, a re-export, + a spec in a subdirectory, and a helper file. `e2e/playwright.config.ts` + is the second exempt file, because it needs `defineConfig` and + `devices`. +3. A test that needs a further browser context opens it with + `newBrowserContext` of `e2e/support.ts`. In Firefox, that context gets + the same init script. The lint rule `no-restricted-properties` for + `e2e/**` fails, outside `e2e/support.ts`, on the property names + `newContext`, `launch`, `launchPersistentContext`, `launchServer`, + `connect`, and `connectOverCDP` on any object, when the code names the + property directly, with a string literal key, or in a destructuring + pattern. It also fails on `browser.newPage`. A page of a context from + the fixture or from `newBrowserContext` gets the init script. +4. Each slice that adds a page or a state with an axe check adds the page + or state to the equivalence test. +5. Chromium and WebKit run unchanged. The journeys use no retry, skip no + engine, and disable no axe rule. + +## Compensating evidence + +`e2e/firefox-aria-reflection.spec.ts` holds these tests. Each test can +fail: + +- Regression (Firefox): a role query with a name, a main-world read of + the property, axe, and a second role query on a page with + `aria-labelledby` do not crash the page. Without the fixture, the test + fails with "Page crashed". +- Challenge (Firefox, with the fixture): axe reports a `button-name` + violation for a button whose `aria-labelledby` names a missing id, and a + pass for a button with a resolved reference. +- Context (Firefox): a second page of the fixture context and a page of a + context from `newBrowserContext` do not have the property in the main + world. +- Equivalence (Chromium and WebKit): on each page and state that a + journey checks with axe, and on the not-found page, in both colour + schemes, the axe violations, passes, and incomplete results are equal + with and without the deletion. The test checks that the property is + present in the control and absent with the deletion. Each case states + whether its page has an element with `aria-labelledby`, and the test + checks that statement; for a page with such an element, it checks that + axe checked a node with `aria-labelledby`. +- Source check (Firefox project, no browser): the application source in + `web/src` and `packages/api-client/src`, without `generated/`, does not + name a property of `HIDDEN_ARIA_REFLECTION_PROPERTIES`. +- Removal guard (Firefox project, no browser): the test fails when the + Firefox revision in `browsers.json` of the pinned `playwright-core` is + 1575 or later. The message tells the reader to remove the workaround + and this exception. + +The lint rules of decisions 2 and 3 support these tests: they keep the +fixture in front of every page. Their known limits: + +- They do not find an `import()` with a computed module name, or a + `require` function from `createRequire`. A literal `import()` fails + `no-restricted-imports`, and a plain `require()` fails + `typescript/no-require-imports`. +- They do not find a computed property name, for example `browser[name]()` + with `const name = 'newContext'`. In Firefox, a page of such a context + does not get the workaround, and no check fails. +- The rule for `newPage` names the object `browser` only. A `Browser` + under another name, or reached through an expression such as + `page.context().browser()`, can call `newPage` without a finding. + `context.newPage()` stays allowed, because the context comes from the + fixture or from `newBrowserContext`. + +## Key alternatives + +- Wait for a stable Playwright release with Firefox build 1575 or later. + Rejected: no such release exists, and the open slices need green + Firefox journeys now. +- Adopt Playwright 1.66 alpha. Rejected: a prerelease needs a reviewed + exception of its own (`DOCTRINE.md` P7), and it changes every browser. +- Downgrade Playwright. Rejected: P7 requires the latest stable release. +- Change the markup (no `aria-labelledby`). Rejected: the accessible name + from the visible heading is the better markup, and a test tool must not + decide the markup. +- Run axe only in Chromium and WebKit. Rejected: it removes the axe check + of one engine completely. +- Exclude the axe rules that read `aria-labelledby`. Rejected: it removes + those checks in every engine. +- Retry the failed journeys. Rejected: a retry hides a failure + (`DOCTRINE.md` P6), and the crash is deterministic. + +## Consequences + +- In Firefox, axe does not check a reference that a script sets only + through the property `ariaLabelledByElements`, with no content + attribute. The application sets no such reference; the source check + enforces this. Chromium and WebKit still check such a reference. +- A context that a test opens with `newBrowserContext` gets the + workaround. A context that bypasses the helper through a gap of the lint + rules does not. +- The journeys do not show whether a stock Firefox 159 crashes for a user, + for example with a browser extension that reads the property in a + second world. This is not verified. + +## Cost of reversal + +Low. Remove the fixture override and the constants from `e2e/support.ts`, +the spec `e2e/firefox-aria-reflection.spec.ts`, the two lint overrides +for `e2e/` in `.oxlintrc.json` if no other reason keeps them, and the row in `STACK.md` +§13. Then set the status of this ADR to "Superseded" or "Expired". + +## Reassessment + +Remove the workaround when a stable Playwright release with Firefox build +1575 or later is older than 1440 minutes, or on 2027-02-28, whichever +comes first. The removal guard fails when the pinned Playwright ships +such a build. diff --git a/e2e/auth-support.ts b/e2e/auth-support.ts index cbbd7a7..d965cb2 100644 --- a/e2e/auth-support.ts +++ b/e2e/auth-support.ts @@ -5,9 +5,10 @@ // tests (playwright.config.ts runs one worker). Call `resetAuth` before a // test that logs in, so the test starts with no session, a full throttle // bucket, and the real clock. -import { expect } from '@playwright/test'; import type { APIRequestContext, Page } from '@playwright/test'; +import { expect } from './support.js'; + /** * The password of the test server. It is a test-only value: the test * server hashes it at each start (playwright.config.ts). It is never a diff --git a/e2e/e4-cookie.spec.ts b/e2e/e4-cookie.spec.ts index 2cdd3a4..9fa0554 100644 --- a/e2e/e4-cookie.spec.ts +++ b/e2e/e4-cookie.spec.ts @@ -9,7 +9,7 @@ // The requests run inside the page with fetch, so the cookie store of the // engine decides. The `request` fixture of Playwright has its own cookie // store and would give the same answer in every engine. -import { expect, test } from '@playwright/test'; +import { expect, test } from './support.js'; type Outcome = { readonly setStatus: number; readonly checkStatus: number; readonly body: unknown }; diff --git a/e2e/firefox-aria-reflection.spec.ts b/e2e/firefox-aria-reflection.spec.ts new file mode 100644 index 0000000..2517c79 --- /dev/null +++ b/e2e/firefox-aria-reflection.spec.ts @@ -0,0 +1,366 @@ +// Compensating evidence of the Firefox ARIA reflection workaround of +// support.ts (ADR 0015, STACK.md §13): +// - the regression test: the two-world read does not crash Firefox; +// - the challenge test: axe in Firefox still checks `aria-labelledby`; +// - the context test: every page of a context of the fixture or of +// newBrowserContext gets the workaround; +// - the equivalence test: in Chromium and WebKit, the deletion does not +// change the axe result of any page and state with an axe check; +// - the source check: the application uses no hidden property; +// - the removal guard: it fails when the pinned Playwright ships a Firefox +// build with the fix. +import { readFileSync, readdirSync, statSync } from 'node:fs'; +import path from 'node:path'; + +import AxeBuilder from '@axe-core/playwright'; +import type { APIRequestContext, Browser, Page } from '@playwright/test'; + +import { TEST_PASSWORD, loginByApi, resetAuth } from './auth-support.js'; +import { + FIXED_FIREFOX_BUILD, + HIDDEN_ARIA_REFLECTION_PROPERTIES, + WCAG_AA_TAGS, + expect, + firefoxExecutablePath, + hideAriaReflection, + newBrowserContext, + pinnedFirefoxBuild, + test, +} from './support.js'; + +const repositoryRoot = path.resolve(import.meta.dirname, '..'); + +/** A page that the test serves with `page.route`; no request reaches the server. */ +async function openRoutedPage(page: Page, body: string): Promise { + await page.route('**/aria-reflection-fixture', (route) => + route.fulfill({ status: 200, contentType: 'text/html', body }), + ); + await page.goto('/aria-reflection-fixture'); +} + +/** True when the main world of the page has the property on Element.prototype. */ +async function hasReflection(page: Page, name: string): Promise { + return page.evaluate((property) => property in Element.prototype, name); +} + +test.describe('Firefox with the workaround', () => { + test.skip(({ browserName }) => browserName !== 'firefox', 'The workaround is active in Firefox only.'); + + test('a role query and a main-world read of ariaLabelledByElements do not crash the page', async ({ page }) => { + let crashed = false; + page.on('crash', () => { + crashed = true; + }); + await openRoutedPage( + page, + 't
' + + '

Otsikko

', + ); + for (const name of HIDDEN_ARIA_REFLECTION_PROPERTIES) { + // Soft, so that a missing workaround also shows the crash below. + expect.soft(await hasReflection(page, name), `${name} must be hidden in the main world`).toBe(false); + } + + // 1. The utility world of Playwright computes the name from aria-labelledby. + await expect(page.getByRole('region', { name: 'Otsikko' })).toHaveCount(1); + // 2. The main world reads the same reflected property, as axe-core does. + const mainWorld = await page.evaluate(() => { + const section = document.querySelector('section'); + if (section === null) { + return 'no section'; + } + const value: unknown = Reflect.get(section, 'ariaLabelledByElements'); + return typeof value; + }); + expect(mainWorld).toBe('undefined'); + // 3. axe-core and a further role query on the same element. + const result = await new AxeBuilder({ page }).withTags(WCAG_AA_TAGS).analyze(); + expect(result.violations).toEqual([]); + await expect(page.getByRole('region', { name: 'Otsikko' })).toHaveCount(1); + expect(crashed).toBe(false); + }); + + test('axe reports an aria-labelledby reference to a missing id and passes a resolved one', async ({ page }) => { + await openRoutedPage( + page, + 't

h

' + + 'Tallenna' + + '' + + '
', + ); + expect(await hasReflection(page, 'ariaLabelledByElements')).toBe(false); + // The utility world still resolves the name of the resolved reference. + await expect(page.getByRole('button', { name: 'Tallenna' })).toHaveCount(1); + + const result = await new AxeBuilder({ page }).withRules(['button-name']).analyze(); + const targets = (kind: 'violations' | 'passes'): string[] => + result[kind].flatMap((rule) => rule.nodes.map((node) => node.target.join(' '))); + expect(targets('violations')).toEqual(['#missing']); + expect(targets('passes')).toEqual(['#resolved']); + }); + + test('a second page of the context and a context of newBrowserContext also hide the property', async ({ + context, + browser, + baseURL, + }) => { + const second = await context.newPage(); + await openRoutedPage(second, 't'); + expect(await hasReflection(second, 'ariaLabelledByElements')).toBe(false); + + if (baseURL === undefined) { + throw new Error('the project has no baseURL'); + } + const other = await newBrowserContext(browser, { baseURL, ignoreHTTPSErrors: true }); + try { + const page = await other.newPage(); + await openRoutedPage(page, 't'); + expect(await hasReflection(page, 'ariaLabelledByElements')).toBe(false); + } finally { + await other.close(); + } + }); + + test('the application source uses no hidden reflection property', () => { + const roots = [path.join(repositoryRoot, 'web', 'src'), path.join(repositoryRoot, 'packages', 'api-client', 'src')]; + const excluded = path.join(repositoryRoot, 'packages', 'api-client', 'src', 'generated'); + const findings = roots.flatMap((root) => findProperties(root, excluded, HIDDEN_ARIA_REFLECTION_PROPERTIES)); + expect( + findings, + 'The Firefox workaround hides these properties in the journeys, so the journeys cannot test their use (ADR 0015).', + ).toEqual([]); + }); + + test('the pinned Playwright has a Firefox build without the fix', () => { + const build = pinnedFirefoxBuild(); + // The browser that the tests launch has the same build. + expect(firefoxExecutablePath()).toContain(`firefox-${String(build)}`); + expect( + build, + `The pinned Playwright ships Firefox build ${String(build)}, which has the fix of Mozilla bug 2090055. ` + + 'Remove the workaround of e2e/support.ts, this spec, the exception row of STACK.md §13, and close ADR 0015.', + ).toBeLessThan(FIXED_FIREFOX_BUILD); + }); +}); + +test.describe('Chromium and WebKit', () => { + test.skip(({ browserName }) => browserName === 'firefox', 'The control run without the workaround crashes Firefox.'); + + type Case = { + readonly name: string; + /** Whether the page of the case has an element with `aria-labelledby`. */ + readonly labelledBy: boolean; + /** Brings a new page of a fresh context into the state of the case. */ + readonly open: (page: Page, baseURL: string) => Promise; + }; + + async function startPage(page: Page, baseURL: string, health?: Parameters[1]): Promise { + await loginByApi(page, baseURL); + if (health !== undefined) { + await fulfillHealth(page, health); + } + await page.goto('/'); + } + + async function fulfillHealth( + page: Page, + health: { readonly status: number; readonly contentType: string; readonly body: string }, + ): Promise { + await page.route('**/health', (route) => route.fulfill(health)); + } + + async function submitPassword(page: Page, password: string): Promise { + await page.getByLabel('Salasana', { exact: true }).fill(password); + await page.getByRole('button', { name: 'Kirjaudu sisään' }).click(); + } + + // Each page and state on main that a journey checks with axe + // (smoke.spec.ts, login.spec.ts), and the not-found page. A slice that + // adds a page or a state with an axe check adds it here (ADR 0015). + const cases: readonly Case[] = [ + { + name: 'protected start page', + labelledBy: false, + open: async (page, baseURL) => { + await startPage(page, baseURL); + await expect(page.getByText('Palvelu toimii.')).toBeVisible(); + }, + }, + { + name: 'start page, unavailable state', + labelledBy: false, + open: async (page, baseURL) => { + await startPage(page, baseURL, { status: 502, contentType: 'text/html', body: 'Bad Gateway' }); + await expect(page.getByText('Tietoja ei saatu')).toBeVisible(); + }, + }, + { + name: 'start page, reload banner', + labelledBy: false, + open: async (page, baseURL) => { + await startPage(page, baseURL, { + status: 200, + contentType: 'application/json', + body: '{"status":"ok","version":"fedcba9"}', + }); + await expect(page.getByText('Sovelluksesta on uusi versio.')).toBeVisible(); + }, + }, + { + name: 'not-found page', + labelledBy: true, + open: async (page, baseURL) => { + await loginByApi(page, baseURL); + await page.goto('/no-such-page'); + await expect(page.getByRole('heading', { level: 1, name: 'Sivua ei löydy' })).toBeVisible(); + }, + }, + { + name: 'login page', + labelledBy: false, + open: async (page) => { + await page.goto('/login'); + await expect(page.getByRole('heading', { level: 1, name: 'Kirjaudu sisään' })).toBeVisible(); + }, + }, + { + name: 'login page, wrong password', + labelledBy: false, + open: async (page) => { + await page.goto('/login'); + await submitPassword(page, 'wrong password, test only'); + await expect(page.getByRole('alert')).toHaveText('Salasana on väärä.'); + }, + }, + { + name: 'login page, throttled', + labelledBy: false, + open: async (page) => { + await page.goto('/login'); + for (let attempt = 0; attempt < 5; attempt += 1) { + await submitPassword(page, `wrong password ${String(attempt)}`); + await expect(page.getByRole('alert')).toHaveText('Salasana on väärä.'); + } + await submitPassword(page, TEST_PASSWORD); + await expect(page.getByRole('alert')).toContainText('Liian monta kirjautumisyritystä.'); + }, + }, + { + name: 'login page, server unavailable', + labelledBy: false, + open: async (page) => { + await page.goto('/login'); + await page.route('**/api/v1/session', (route) => + route.request().method() === 'POST' + ? route.fulfill({ status: 502, contentType: 'text/html', body: 'Bad Gateway' }) + : route.fallback(), + ); + await submitPassword(page, TEST_PASSWORD); + await expect(page.getByRole('alert')).toContainText('Kirjautuminen ei onnistunut.'); + }, + }, + { + name: 'logout failure view', + labelledBy: false, + open: async (page, baseURL) => { + await startPage(page, baseURL); + await expect(page.getByText('Palvelu toimii.')).toBeVisible(); + await page.route('**/api/v1/session', (route) => + route.request().method() === 'DELETE' ? route.abort('failed') : route.fallback(), + ); + await page.getByRole('button', { name: 'Kirjaudu ulos' }).click(); + await expect(page.getByRole('heading', { level: 1, name: 'Uloskirjautuminen ei onnistunut' })).toBeVisible(); + }, + }, + ]; + + for (const testCase of cases) { + test(`the deletion does not change the axe result: ${testCase.name}`, async ({ browser, baseURL, request }) => { + if (baseURL === undefined) { + throw new Error('the project has no baseURL'); + } + const control = await axeSummary(browser, baseURL, request, testCase, false); + const treatment = await axeSummary(browser, baseURL, request, testCase, true); + expect(control.reflection, 'the control has the property').toBe(true); + expect(treatment.reflection, 'the deletion removes the property').toBe(false); + expect(control.labelledByElements > 0, 'the page has an element with aria-labelledby').toBe(testCase.labelledBy); + if (testCase.labelledBy) { + expect(control.labelledByNodes, 'axe checked a node with aria-labelledby').toBeGreaterThan(0); + } + expect(treatment.result).toEqual(control.result); + }); + } + + async function axeSummary( + browser: Browser, + baseURL: string, + request: APIRequestContext, + testCase: Case, + deletion: boolean, + ): Promise<{ + readonly reflection: boolean; + readonly labelledByElements: number; + readonly labelledByNodes: number; + readonly result: string[]; + }> { + // Each run starts with no session, a full throttle bucket, and the real clock. + await resetAuth(request); + const context = await newBrowserContext(browser, { baseURL, ignoreHTTPSErrors: true }); + try { + if (deletion) { + await hideAriaReflection(context); + } + const page = await context.newPage(); + await testCase.open(page, baseURL); + const reflection = await hasReflection(page, 'ariaLabelledByElements'); + const labelledByElements = await page.locator('[aria-labelledby]').count(); + const result: string[] = []; + let labelledByNodes = 0; + for (const colorScheme of ['light', 'dark'] as const) { + await page.emulateMedia({ colorScheme }); + const axe = await new AxeBuilder({ page }).withTags(WCAG_AA_TAGS).analyze(); + for (const kind of ['violations', 'passes', 'incomplete'] as const) { + for (const rule of axe[kind]) { + for (const node of rule.nodes) { + if (node.html.includes('aria-labelledby')) { + labelledByNodes += 1; + } + const checks = [...node.any, ...node.all, ...node.none].map((check) => `${check.id}:${check.message}`); + result.push( + `${colorScheme} ${kind} ${rule.id} ${node.target.join(' ')} ${String(node.impact)} ${checks.sort().join(',')}`, + ); + } + } + } + } + return { reflection, labelledByElements, labelledByNodes, result: result.sort() }; + } finally { + await context.close(); + } + } +}); + +/** Each `file: property` pair where a file under `root` names a property. */ +function findProperties(root: string, excluded: string, properties: readonly string[]): string[] { + const findings: string[] = []; + const visit = (directory: string): void => { + for (const entry of readdirSync(directory)) { + const file = path.join(directory, entry); + if (file === excluded) { + continue; + } + if (statSync(file).isDirectory()) { + visit(file); + continue; + } + const text = readFileSync(file, 'utf8'); + for (const property of properties) { + if (text.includes(property)) { + findings.push(`${path.relative(repositoryRoot, file)}: ${property}`); + } + } + } + }; + visit(root); + return findings; +} diff --git a/e2e/login.spec.ts b/e2e/login.spec.ts index e779224..68348ef 100644 --- a/e2e/login.spec.ts +++ b/e2e/login.spec.ts @@ -8,11 +8,18 @@ import process from 'node:process'; import AxeBuilder from '@axe-core/playwright'; -import { expect, test } from '@playwright/test'; import type { APIRequestContext, BrowserContext, Page } from '@playwright/test'; import { SESSION_COOKIE, TEST_PASSWORD, advanceClock, authStats, loginByApi, resetAuth } from './auth-support.js'; -import { WCAG_AA_TAGS, cspViolations, recordCspViolations, recordForeignRequests } from './support.js'; +import { + WCAG_AA_TAGS, + cspViolations, + expect, + newRequestContext, + recordCspViolations, + recordForeignRequests, + test, +} from './support.js'; const SEVEN_DAYS = 7 * 86_400; @@ -96,7 +103,7 @@ test('a stolen copy of the cookie stops working after logout', async ({ page, co const cookie = await sessionCookie(context); expect(cookie).toBeDefined(); const copy = `${SESSION_COOKIE}=${cookie?.value ?? ''}`; - const thief = await playwright.request.newContext({ + const thief = await newRequestContext(playwright.request, { baseURL: baseURL ?? '', ignoreHTTPSErrors: true, extraHTTPHeaders: { cookie: copy }, diff --git a/e2e/smoke.spec.ts b/e2e/smoke.spec.ts index b86e297..7f612c8 100644 --- a/e2e/smoke.spec.ts +++ b/e2e/smoke.spec.ts @@ -5,11 +5,18 @@ import process from 'node:process'; import AxeBuilder from '@axe-core/playwright'; -import { expect, test } from '@playwright/test'; import type { Page } from '@playwright/test'; import { loginByApi, resetAuth } from './auth-support.js'; -import { SERVER_VERSION, WCAG_AA_TAGS, cspViolations, recordCspViolations, recordForeignRequests } from './support.js'; +import { + SERVER_VERSION, + WCAG_AA_TAGS, + cspViolations, + expect, + recordCspViolations, + recordForeignRequests, + test, +} from './support.js'; test.beforeEach(async ({ page, request, baseURL }) => { await resetAuth(request); diff --git a/e2e/support.ts b/e2e/support.ts index de11ed2..232c802 100644 --- a/e2e/support.ts +++ b/e2e/support.ts @@ -1,5 +1,24 @@ -// Shared helpers of the browser journeys. -import type { Page } from '@playwright/test'; +// Shared fixture and helpers of the browser journeys. This file is the +// only e2e file that imports values from Playwright; every other e2e file +// imports types only and takes `test`, `expect`, and the context helpers +// from here. It is also the only e2e file that opens a browser context or +// an API request context itself. The lint rules no-restricted-imports and +// no-restricted-properties for `e2e/**` in .oxlintrc.json enforce both. +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import path from 'node:path'; + +import { test as base, expect, firefox } from '@playwright/test'; +import type { + APIRequest, + APIRequestContext, + Browser, + BrowserContext, + BrowserContextOptions, + Page, +} from '@playwright/test'; + +export { expect }; /** The version that the test server reports, in /health and in index.html. */ export const SERVER_VERSION = '0123abc'; @@ -45,3 +64,114 @@ export function recordForeignRequests(page: Page, baseURL: string): string[] { }); return foreign; } + +/** + * The ARIA element-reflection properties that the Firefox workaround + * deletes from `Element.prototype` (ADR 0015). The Firefox of Playwright + * 1.65.1 (Firefox 159.0, build 1572) crashes its content process when + * Playwright's utility world and the page's main world both read + * `ariaLabelledByElements` of one element (Mozilla bug 2090055). The + * utility world reads no other reflection property, so the list holds + * only this one. + */ +export const HIDDEN_ARIA_REFLECTION_PROPERTIES: readonly string[] = ['ariaLabelledByElements']; + +/** + * The first Firefox build of Playwright that has the fix of Mozilla bug + * 2090055 (Playwright PR 43982). The removal guard in + * firefox-aria-reflection.spec.ts fails from this build on. + */ +export const FIXED_FIREFOX_BUILD = 1575; + +/** + * Deletes the properties of HIDDEN_ARIA_REFLECTION_PROPERTIES in the main + * world of each page of the context, before any page script runs. axe-core + * then reads `aria-labelledby` from the content attribute. Playwright's + * utility world is a separate JavaScript world; its role queries still + * resolve a name from `aria-labelledby` (firefox-aria-reflection.spec.ts). + */ +export async function hideAriaReflection(context: BrowserContext): Promise { + await context.addInitScript((names: readonly string[]) => { + for (const name of names) { + Reflect.deleteProperty(Element.prototype, name); + } + }, HIDDEN_ARIA_REFLECTION_PROPERTIES); +} + +/** + * The test function of every journey. In the Firefox project only, the + * context fixture hides the ARIA element reflection of + * HIDDEN_ARIA_REFLECTION_PROPERTIES, so that axe-core in the main world + * and the role queries of Playwright do not crash the content process. + * Chromium and WebKit run unchanged. The workaround is a scoped exception + * (ADR 0015, STACK.md §13). Remove it when the pinned Playwright ships + * Firefox build FIXED_FIREFOX_BUILD or later; the removal guard fails then. + * A test that needs a further browser context opens it with + * `newBrowserContext`, which applies the same workaround. + */ +export const test = base.extend({ + // The second argument is Playwright's `use`, named `provide` so that the + // React hook rule does not read it as a hook call. + context: async ({ context, browserName }, provide) => { + if (browserName === 'firefox') { + await hideAriaReflection(context); + } + await provide(context); + }, +}); + +/** + * Opens a new browser context. In Firefox, the context gets the workaround + * of the `context` fixture. Use it instead of `browser.newContext()`. + */ +export async function newBrowserContext(browser: Browser, options: BrowserContextOptions): Promise { + const context = await browser.newContext(options); + if (browser.browserType().name() === 'firefox') { + await hideAriaReflection(context); + } + return context; +} + +/** + * Opens a new API request context. An API request context has no page, so + * the workaround does not apply; the helper exists so that only this file + * calls `newContext`. + */ +export async function newRequestContext( + request: APIRequest, + options: Parameters[0], +): Promise { + return request.newContext(options); +} + +/** The path of the Firefox executable that the tests launch. */ +export function firefoxExecutablePath(): string { + return firefox.executablePath(); +} + +/** The Firefox build that browsers.json of the pinned playwright-core names. */ +export function pinnedFirefoxBuild(): number { + // playwright-core is a dependency of playwright, which is a dependency of + // @playwright/test; pnpm links only the direct dependencies. + const fromTest = createRequire(createRequire(import.meta.url).resolve('@playwright/test/package.json')); + const fromPlaywright = createRequire(fromTest.resolve('playwright/package.json')); + const corePackage = fromPlaywright.resolve('playwright-core/package.json'); + const parsed: unknown = JSON.parse(readFileSync(path.join(path.dirname(corePackage), 'browsers.json'), 'utf8')); + if (typeof parsed !== 'object' || parsed === null || !('browsers' in parsed) || !Array.isArray(parsed.browsers)) { + throw new Error('browsers.json of playwright-core has no browsers list'); + } + const entries: unknown[] = parsed.browsers; + const entry = entries.find( + (candidate): candidate is { name: string; revision: string } => + typeof candidate === 'object' && + candidate !== null && + 'name' in candidate && + candidate.name === 'firefox' && + 'revision' in candidate && + typeof candidate.revision === 'string', + ); + if (entry === undefined || !/^\d+$/.test(entry.revision)) { + throw new Error('browsers.json of playwright-core has no Firefox entry with a numeric revision'); + } + return Number.parseInt(entry.revision, 10); +}