diff --git a/README.md b/README.md index 56ae20f..5505d79 100644 --- a/README.md +++ b/README.md @@ -83,7 +83,16 @@ npm install --save-dev buttonmash npx playwright install --with-deps chromium # one-time browser install ``` -Requires Node 20+. +Requires Node 20+. Playwright 1.65 no longer tests on Node 20, so prefer 22 or +newer. + +buttonmash runs on Playwright 1.64.1 or newer, and uses your project's copy +when that version fits. If your project pins an older Playwright, npm gives +buttonmash a copy of its own, and a bare `npx playwright install` then +downloads browsers for your copy instead. `buttonmash doctor` reports which +Playwright buttonmash loads, and when its browser is missing, `doctor` and +`run` print the command that installs it, such as +`npx playwright@1.64.1 install --with-deps chromium`. ## Quickstart @@ -140,14 +149,14 @@ jobs: steps: - uses: actions/checkout@v5 # start your app under test here (e.g. npm ci && npm run start &) and wait for it… - - uses: cj-vana/buttonmash@v0.3.1 + - uses: cj-vana/buttonmash@v0.4.0 with: target: http://localhost:3000 args: --seed ci --max-actions 800 ``` -The action runs the buttonmash release that matches its own tag (`@v0.3.1` -installs 0.3.1) and reads a committed `buttonmash.config.*` from the +The action runs the buttonmash release that matches its own tag (`@v0.4.0` +installs 0.4.0) and reads a committed `buttonmash.config.*` from the workspace. Its inputs: | Input | Default | What it does | @@ -259,7 +268,8 @@ Salesforce LWC, Ionic, Shoelace/Lit/Material Web) and **same-origin iframes** (embedded editors, wizards), so component-based apps aren't invisible to it. It also skips what a user couldn't reach: the contents of a closed `
`, inert subtrees, and, while a modal dialog is open, everything outside the top -modal. +modal. The same holds for an iframe: nothing inside it is offered when the +iframe is hidden, inert, or outside an open modal. It's built to survive messy real apps on long CI sweeps: it **recovers from renderer crashes** (recreates the page and continues, skipping the page that @@ -338,6 +348,10 @@ export default defineConfig({ billing: { mode: 'refuse' }, // refuse | warn | off // dryRun: true, // read-only: explore without submitting // vetRedirects: true, // check a page's first redirect before following it + // blockedRequests: [ // refuse by HTTP method, path (regex), or both + // { method: 'DELETE' }, + // { method: 'POST', path: '^/api/admin/' }, + // ], destructive: { enabled: true, extraVerbs: ['archivar'], @@ -405,7 +419,10 @@ loops, React dev warnings, HMR…) and **downgrades third-party `console.error`* errors stay high (`detectors.thirdPartyConsole: true` to opt in). State dedup is **structural** by default, so live counters/clocks don't explode the state space on dynamic apps. Requests buttonmash's own fence blocks (a web font under -`blockMedia`, a logout ping) are never reported as app errors, in any engine. A +`blockMedia`, a logout ping) are never reported as app errors, in any engine; +the logout ping shows up as an `info` fence finding instead (see Safety). +Neither is a request cancelled before it finished, such as a navigation a +double-click restarted or a fetch the page aborted. A control another layer covers (a canvas, a stuck overlay) costs one timeout per page, not one per pick. And if CI cancels or times out mid-run (SIGINT or SIGTERM), a **partial report is still written** with exit code `2`, so you never @@ -425,6 +442,19 @@ buttonmash is built to break things without breaking *you*: then the fence checks each page's first redirect before it is followed (Chromium and Firefox), at the cost of fetching every page itself, which buffers it and drops its `Sec-Fetch-*` headers. +- **Fence writes by method.** `guardrails.blockedRequests` refuses requests by + HTTP method, path, or both, so `{ method: 'DELETE' }` stops every delete + while reads of the same path still load. `path` is a regex matched like a + `blockedPathPatterns` entry, and both parts must match when a rule has both. + A rule that refuses a GET also keeps the crawl and link clicks off its path. + Like path guards, rules never block scripts, styles, images, fonts or media. +- **Show what the fence blocked.** Each request the fence refuses, whether by a + path guard, a `blockedRequests` rule or another origin, becomes an `info` + finding in the `fence` category: one per route (one per origin for page + loads), with a count. At the default `failOn` it doesn't fail the run, but it + shows when the fence stopped something it shouldn't have. Fonts and media + dropped by `blockMedia` aren't reported, and a payment provider's pages are + left to the billing guard. - **Skip destructive controls.** Buttons/links matching a multilingual verb list (delete, pay, logout, cancel subscription, …), or pointing at dangerous paths (`/logout`, `/account/delete`, `/billing/cancel`), are detected and diff --git a/package-lock.json b/package-lock.json index 0c213da..6e5d20e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,19 +1,19 @@ { "name": "buttonmash", - "version": "0.3.1", + "version": "0.4.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "buttonmash", - "version": "0.3.1", + "version": "0.4.0", "license": "MIT", "dependencies": { "axe-core": "^4.10.2", "commander": "^12.1.0", "jiti": "^2.4.2", "picocolors": "^1.1.1", - "playwright": "^1.49.1", + "playwright": "^1.64.1", "zod": "^3.24.1" }, "bin": { @@ -3455,12 +3455,12 @@ } }, "node_modules/playwright": { - "version": "1.63.0", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", - "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.63.0" + "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" @@ -3470,9 +3470,9 @@ } }, "node_modules/playwright-core": { - "version": "1.63.0", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", - "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" diff --git a/package.json b/package.json index 9b88614..8de5ded 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "buttonmash", - "version": "0.3.1", + "version": "0.4.0", "description": "A CI chaos monkey for web apps. It presses every button, mashes random keystrokes, tries to break your UI, and reports what it found. Safe by default.", "keywords": [ "chaos-monkey", @@ -64,7 +64,7 @@ "commander": "^12.1.0", "jiti": "^2.4.2", "picocolors": "^1.1.1", - "playwright": "^1.49.1", + "playwright": "^1.64.1", "zod": "^3.24.1" }, "devDependencies": { diff --git a/src/cli-program.ts b/src/cli-program.ts index d31f832..b211354 100644 --- a/src/cli-program.ts +++ b/src/cli-program.ts @@ -14,7 +14,12 @@ import { runDoctor } from './doctor'; import { runButtonmash } from './explorer/runner'; import { writeReports } from './report'; import { captureAuth } from './session/auth'; -import type { Engine } from './session/browser'; +import { + browserInstallCommand, + isMissingBrowser, + playwrightVersion, + type Engine, +} from './session/browser'; import { version } from './version'; interface RunOpts { @@ -183,6 +188,8 @@ async function doRun( opts: RunOpts, replayed: Partial = {}, ): Promise { + // The config file can choose the engine too, so the hint below reads it once loaded. + let engine: Engine = opts.browser ?? 'chromium'; try { if (opts.failOn && !(opts.failOn in SEVERITY_ORDER)) { throw new ConfigError(`--fail-on must be one of: ${Object.keys(SEVERITY_ORDER).join(', ')}`); @@ -194,6 +201,7 @@ async function doRun( // config file's lists rather than replacing them. append: { routes: opts.route, allowedOrigins: opts.allowOrigin }, }); + engine = cfg.browser; const { result, outDir } = await runButtonmash(cfg); await writeReports(result, outDir, cfg); printSummary(result, outDir, cfg.report.formats.includes('html')); @@ -202,9 +210,11 @@ async function doRun( const message = (err as Error).message ?? String(err); if (err instanceof ConfigError || err instanceof BaselineError) { logger.error(message); - } else if (/Executable doesn't exist|playwright install|browserType\.launch/i.test(message)) { - logger.error('The browser is not installed.'); - logger.info(`Run: npx playwright install --with-deps ${opts.browser ?? 'chromium'}`); + } else if (isMissingBrowser(message)) { + logger.error(`${engine} is not installed for Playwright ${playwrightVersion}.`); + logger.info(`Run: ${browserInstallCommand(engine)}`); + } else if (/browserType\.launch/.test(message)) { + logger.error(`${engine} could not start: ${message.split('\n')[0]}`); } else { logger.error(`buttonmash crashed: ${(err as Error).stack ?? message}`); } @@ -423,6 +433,8 @@ export default defineConfig({ // Refuse to run if LIVE Stripe/Braintree keys are detected. Use test mode! billing: { mode: 'refuse' }, // dryRun: true, // read-only: explore without submitting/mutating + // Refuse requests by HTTP method, path (regex), or both. Reads still load. + // blockedRequests: [{ method: 'DELETE' }, { method: 'POST', path: '^/api/admin/' }], // Controls whose names only look destructive (regex), e.g. a canvas "Reset zoom". // destructive: { safeNames: ['^reset zoom$'] }, }, diff --git a/src/config/schema.ts b/src/config/schema.ts index 39b1279..bb3a636 100644 --- a/src/config/schema.ts +++ b/src/config/schema.ts @@ -191,12 +191,34 @@ const SecretsSchema = z }) .default({}); +/** One request the fence refuses. Both parts are optional, and when both are + * given both must match: `{ method: 'DELETE' }` refuses every delete, while + * `{ method: 'POST', path: '^/api/admin/' }` refuses only admin writes. */ +const BlockedRequestSchema = z + .object({ + /** HTTP method, in any case. */ + method: z + .string() + .regex(/^[A-Za-z]+$/, 'must be an HTTP method such as POST or DELETE') + .transform((method) => method.toUpperCase()) + .optional(), + /** Regex for the path with its query, matched as blockedPathPatterns are. */ + path: RegexSchema.optional(), + }) + .refine((rule) => rule.method !== undefined || rule.path !== undefined, { + message: 'needs a method, a path, or both', + }); + const GuardrailsSchema = z .object({ /** Origins the monkey may navigate to. Empty → just the target's origin. */ allowedOrigins: z.array(z.string()).default([]), /** Extra regex strings for paths to hard-block, even on allowed origins. */ blockedPathPatterns: z.array(RegexSchema).default([]), + /** Requests to refuse by HTTP method, path, or both. Unlike a blocked path, + * a rule with a method leaves the path's other methods alone, so a read + * of the same path still loads. */ + blockedRequests: z.array(BlockedRequestSchema).default([]), /** If non-empty, only crawl paths matching one of these regexes (scope a * sweep to e.g. ^/app/). */ includePaths: z.array(RegexSchema).default([]), diff --git a/src/core/types.ts b/src/core/types.ts index e06551b..a8e2527 100644 --- a/src/core/types.ts +++ b/src/core/types.ts @@ -186,6 +186,7 @@ export type SignalKind = | 'form-validation' | 'session-lost' | 'guardrail' + | 'fence' | 'custom' | 'driver'; diff --git a/src/detectors/aggregate.ts b/src/detectors/aggregate.ts index 21d17d9..cfd1d1a 100644 --- a/src/detectors/aggregate.ts +++ b/src/detectors/aggregate.ts @@ -67,18 +67,21 @@ const KIND_META: Record = { label: 'Session lost (logged out mid-run)', }, guardrail: { category: 'guardrail', defaultSeverity: 'info', label: 'Guardrail' }, + fence: { category: 'fence', defaultSeverity: 'info', label: 'Blocked by the fence' }, custom: { category: 'custom', defaultSeverity: 'medium', label: 'Custom rule' }, driver: { category: 'driver-error', defaultSeverity: 'medium', label: 'Driver error' }, }; /** Network failures are resource-scoped, not page-scoped: the same broken * asset/endpoint (its URL is in the detail) referenced from ten pages is one - * bug, not ten findings — so these kinds drop the page URL from their key. */ + * bug, not ten findings, so these kinds drop the page URL from their key. + * A fence block is the same: one finding per blocked route. */ const RESOURCE_KINDS = new Set([ 'http.4xx', 'http.5xx', 'requestfailed', 'broken-image', + 'fence', ]); /** The part of a signal's detail that identifies the bug. An axe violation's diff --git a/src/detectors/signals.ts b/src/detectors/signals.ts index 3334d34..11ebffd 100644 --- a/src/detectors/signals.ts +++ b/src/detectors/signals.ts @@ -119,7 +119,16 @@ export function attachSignalListeners(deps: SignalDeps): void { const errorText = req.failure()?.errorText ?? 'unknown'; // Ignore the navigations/resources WE aborted via the fence. if (fenced.has(req.url())) return; - if (/ERR_ABORTED|BLOCKED_BY_CLIENT|blockedbyclient/i.test(errorText)) return; + // A request cancelled before it finished (a restarted navigation, an + // aborted fetch) did not fail: Chromium net::ERR_ABORTED, Firefox + // NS_BINDING_ABORTED, WebKit "cancelled". + if ( + /ERR_ABORTED|NS_BINDING_ABORTED|^cancelled$|BLOCKED_BY_CLIENT|blockedbyclient/i.test( + errorText, + ) + ) { + return; + } if (!cfg.detectors.httpErrors) return; const line = `${req.method()} ${req.url()} — ${errorText}`; if (ignored(line)) return; diff --git a/src/doctor.ts b/src/doctor.ts index f621f58..1c21047 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -13,10 +13,21 @@ import { combineRegexes, compileRegexes } from './core/regex'; import { SignalRecorder } from './detectors/recorder'; import { inspectRequestForLiveMode, scanTextForLiveMode } from './guardrails/billing'; import { DANGEROUS_PATH_RE } from './guardrails/destructive'; -import { attachPageFence, installContextFence, isAllowedOrigin } from './guardrails/fence'; +import { + attachPageFence, + compileRequestRules, + installContextFence, + isAllowedOrigin, +} from './guardrails/fence'; import { redactString } from './guardrails/secrets'; import { performScriptedLogin, validateStorageState } from './session/auth'; -import { createDeterministicContext, launchBrowser } from './session/browser'; +import { + browserInstallCommand, + createDeterministicContext, + isMissingBrowser, + launchBrowser, + playwrightVersion, +} from './session/browser'; import { version } from './version'; export type DoctorStatus = 'pass' | 'warn' | 'fail'; @@ -111,9 +122,17 @@ export async function runDoctor(cfg: ResolvedConfig): Promise { browser = await launchBrowser(cfg.browser, true, { vetRedirects: cfg.guardrails.vetRedirects, }); - check(checks, 'browser', 'pass', `${cfg.browser} launched successfully`); + check(checks, 'browser', 'pass', `${cfg.browser} launched (Playwright ${playwrightVersion})`); } catch (err) { - check(checks, 'browser', 'fail', `${cfg.browser} could not launch: ${(err as Error).message}`); + const message = (err as Error).message; + check( + checks, + 'browser', + 'fail', + isMissingBrowser(message) + ? `${cfg.browser} is not installed for Playwright ${playwrightVersion}. Run: ${browserInstallCommand(cfg.browser)}` + : `${cfg.browser} could not launch: ${message}`, + ); return { ok: false, checks }; } @@ -144,6 +163,7 @@ export async function runDoctor(cfg: ResolvedConfig): Promise { const fenceOptions = { allowedOrigins: cfg.guardrails.allowedOrigins, blockedPathRe: combineRegexes(pathRegexes), + blockedRequests: compileRequestRules(cfg.guardrails.blockedRequests), blockMedia: cfg.guardrails.blockMedia, billingMode: cfg.guardrails.billing.mode, isBillingLatched: () => billingLatched, diff --git a/src/explorer/actions.ts b/src/explorer/actions.ts index 6150ef4..b2a195e 100644 --- a/src/explorer/actions.ts +++ b/src/explorer/actions.ts @@ -13,6 +13,7 @@ import { combineRegexes, compileRegexes } from '../core/regex'; import type { Rng } from '../core/rng'; import type { ActionKind, ElementDescriptor, FormDescriptor } from '../core/types'; import { classifyControl } from '../guardrails/destructive'; +import { navigationBlockedPatterns } from '../guardrails/fence'; import type { SignalRecorder } from '../detectors/recorder'; import { addCanary, type DetectorState } from '../detectors/page-checks'; import { locate } from './discover'; @@ -163,7 +164,7 @@ export function gatePlan(plan: Plan, cfg: ResolvedConfig, recorder: SignalRecord // A link into a path the user blocked. The fence stops a real navigation // there, but not a hash-router or pushState route. - const blockedPaths = combineRegexes(compileRegexes(cfg.guardrails.blockedPathPatterns)); + const blockedPaths = combineRegexes(compileRegexes(navigationBlockedPatterns(cfg.guardrails))); if (el?.href && blockedPaths && MUTATING.has(kind)) { let dest: URL | undefined; try { diff --git a/src/explorer/discover.ts b/src/explorer/discover.ts index d64b8bd..78c1192 100644 --- a/src/explorer/discover.ts +++ b/src/explorer/discover.ts @@ -5,7 +5,7 @@ * contenteditable controls, filter to actionable ones, and build a stable * fingerprint and a locator for each. */ -import type { Frame, Locator, Page } from 'playwright'; +import type { ElementHandle, Frame, Locator, Page } from 'playwright'; import { withDeadline } from '../core/async'; import { elementFingerprint, structuralFingerprint } from '../core/hash'; @@ -38,11 +38,20 @@ export const INTERACTIVE_SELECTOR = [ type RawDescriptor = Omit; +interface Collected { + items: RawDescriptor[]; + /** For each element in `frames`, whether a user could reach the iframe. */ + frames: boolean[]; +} + /** Runs in the browser (per document/frame); returns serializable descriptors * for visible controls, piercing OPEN shadow roots. Shadow-DOM elements are * tagged with an ephemeral [data-bm-id] so Playwright (whose CSS engine pierces - * open shadow roots) can relocate them; light-DOM elements keep an nth-child path. */ -function collect(arg: { selector: string; framePrefix: string }): RawDescriptor[] { + * open shadow roots) can relocate them; light-DOM elements keep an nth-child path. + * `frames` are this document's ' + + '', + ), + ).toEqual(['Shown frame']); + }); + + it('skips controls in an inert iframe and under an inert ancestor', async () => { + expect( + await namesOn( + '' + + '
' + + '', + ), + ).toEqual(['Awake']); + }); + + it('skips a frame nested in a hidden frame', async () => { + expect( + await namesOn( + `` + + '', + ), + ).toEqual(['Outside']); + }); + + it('keeps only the frames inside an open modal dialog', async () => { + expect( + await namesOn( + '' + + '', + (page) => + page.evaluate(() => (document.getElementById('d') as HTMLDialogElement).showModal()), + ), + ).toEqual(['In the dialog']); + }); +}); + describe('discovery under a modal dialog', () => { it('offers only the controls of an open aria-modal dialog', async () => { expect( diff --git a/test/fence-billing.test.ts b/test/fence-billing.test.ts index 4ff8cee..ac4a299 100644 --- a/test/fence-billing.test.ts +++ b/test/fence-billing.test.ts @@ -16,6 +16,7 @@ type Handler = (route: Route) => unknown; function fakeRequest(url: string, resourceType = 'script'): Request { return { url: () => url, + method: () => 'GET', resourceType: () => resourceType, postData: () => null, } as unknown as Request; diff --git a/test/fence-browser.test.ts b/test/fence-browser.test.ts index dfd50ef..8f97bd2 100644 --- a/test/fence-browser.test.ts +++ b/test/fence-browser.test.ts @@ -9,11 +9,13 @@ import { createServer, type Server } from 'node:http'; import { chromium, type Browser, type BrowserContext, type Page } from 'playwright'; import { combineRegexes } from '../src/core/regex'; +import { aggregateFindings } from '../src/detectors/aggregate'; import { SignalRecorder } from '../src/detectors/recorder'; import { DANGEROUS_PATH_RE } from '../src/guardrails/destructive'; import { FenceLog, attachPageFence, + compileRequestRules, installContextFence, type FenceOptions, } from '../src/guardrails/fence'; @@ -209,6 +211,98 @@ describe('dangerous routes outside the pathname', () => { }); }); +describe('blockedRequests', () => { + /** Send `method` to `path` from the page, as an app's fetch would. */ + const send = (method: string, path: string) => + page.evaluate( + ([m, p]) => + fetch(p as string, { method: m as string }).then( + () => 'sent', + () => 'refused', + ), + [method, path], + ); + const fenceNotes = () => recorder.signals.filter((s) => s.kind === 'fence').map((s) => s.detail); + + it('refuses a method on a path while a read of the same path goes through', async () => { + await setUp({ blockedRequests: compileRequestRules([{ method: 'delete' }]) }); + expect(await send('DELETE', '/api/workspace')).toBe('refused'); + expect(await send('GET', '/api/workspace')).toBe('sent'); + expect(requested()).toEqual([`GET 127.0.0.1:${port}/api/workspace`]); + expect(fenceNotes()).toEqual([`DELETE ${base}/api/workspace (guardrails.blockedRequests[0])`]); + }); + + it('refuses a method the page sends in lower case', async () => { + // fetch() upper-cases only the standard methods, so this goes out as + // "patch", which servers commonly route as PATCH. + await setUp({ blockedRequests: compileRequestRules([{ method: 'PATCH' }]) }); + expect(await send('patch', '/api/workspace')).toBe('refused'); + expect(requested()).toEqual([]); + expect(fenceNotes()).toEqual([`patch ${base}/api/workspace (guardrails.blockedRequests[0])`]); + }); + + it('needs both the method and the path when a rule has both', async () => { + await setUp({ + blockedRequests: compileRequestRules([{ method: 'POST', path: '^/api/admin/' }]), + }); + expect(await send('POST', '/api/admin/users')).toBe('refused'); + expect(await send('GET', '/api/admin/users')).toBe('sent'); + expect(await send('POST', '/api/notes')).toBe('sent'); + expect(requested()).toEqual([ + `GET 127.0.0.1:${port}/api/admin/users`, + `POST 127.0.0.1:${port}/api/notes`, + ]); + }); + + it('closes a socket whose handshake a path rule refuses', async () => { + await setUp({ blockedRequests: compileRequestRules([{ path: '^/live' }]) }); + const ended = await page.evaluate( + (target) => + new Promise((resolve) => { + const ws = new WebSocket(target); + ws.onclose = (event) => resolve(`closed ${event.code}`); + setTimeout(() => resolve('pending'), 2_000); + }), + `ws://127.0.0.1:${port}/live`, + ); + expect(ended).toBe('closed 1008'); + await settle(); + expect(requested()).toEqual([]); + expect(fenceNotes()).toEqual([ + `WebSocket ws://127.0.0.1:${port}/live (guardrails.blockedRequests[0])`, + ]); + }); + + it('reports blocked paths and page loads from other origins, not media blocking', async () => { + await setUp({ blockMedia: true }); + expect(await send('POST', '/logout')).toBe('refused'); + await page.evaluate(() => new FontFace('brand', 'url(/brand.woff2)').load().catch(() => {})); + await expect(page.goto(`${offsite}/elsewhere`)).rejects.toThrow(/ERR_BLOCKED_BY_CLIENT/); + await settle(); + expect(fenced.has(`${base}/brand.woff2`)).toBe(true); + expect(fenceNotes()).toEqual([ + `POST ${base}/logout (blocked path)`, + `page load from ${offsite}, outside the allowed origins`, + ]); + }); + + it('groups blocks of one route from different pages into one finding', async () => { + await setUp({ blockedRequests: compileRequestRules([{ method: 'DELETE' }]) }); + for (const from of ['/start', '/other']) { + await page.goto(`${base}${from}`); + recorder.setContext(0, page.url()); + await send('DELETE', '/api/things/48213'); + await send('DELETE', '/api/things/59724'); + } + const findings = aggregateFindings({ + signals: recorder.signals, + actions: [], + screenshots: new Map(), + }); + expect(findings.map((f) => [f.category, f.severity, f.count])).toEqual([['fence', 'info', 4]]); + }); +}); + describe('commits with an opaque origin', () => { it('does not report or undo the error page Chromium shows for a fenced navigation', async () => { await expect(page.goto(`${offsite}/elsewhere`)).rejects.toThrow(/ERR_BLOCKED_BY_CLIENT/); diff --git a/test/fence-noise.test.ts b/test/fence-noise.test.ts index 34ccb97..c597600 100644 --- a/test/fence-noise.test.ts +++ b/test/fence-noise.test.ts @@ -14,8 +14,14 @@ import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { buttonmash } from '../src/index'; +import { chromium, firefox, webkit } from 'playwright'; + +import { loadConfig } from '../src/config/load'; import type { RunResult } from '../src/core/types'; +import { SignalRecorder } from '../src/detectors/recorder'; +import { attachSignalListeners } from '../src/detectors/signals'; +import { FenceLog } from '../src/guardrails/fence'; +import { buttonmash } from '../src/index'; import type { Engine } from '../src/session/browser'; import { startServer, type TestServer } from './helpers/server'; @@ -68,3 +74,43 @@ describe(`requests the fence aborts (${browser})`, () => { expect(result.run.exitCode).toBe(0); }); }); + +describe(`requests cancelled before they finish (${browser})`, () => { + // A double-clicked link restarts its navigation and a page can abort its own + // fetch. Chromium calls that net::ERR_ABORTED, Firefox NS_BINDING_ABORTED, + // WebKit "cancelled"; none of them is a failed request. + it('are not reported as failed network requests', async () => { + const cfg = await loadConfig({ + ignoreConfigFile: true, + overrides: { target: server.url, browser, logLevel: 'silent' }, + }); + const instance = await { chromium, firefox, webkit }[browser].launch(); + try { + const page = await instance.newPage(); + const recorder = new SignalRecorder(); + const reported: string[] = []; + page.on('requestfailed', (req) => reported.push(req.failure()?.errorText ?? '')); + attachSignalListeners({ + page, + recorder, + cfg, + ignore: [], + customConsole: [], + onBillingLive: () => {}, + fenced: new FenceLog(), + }); + await page.goto(`${server.url}/fonts`); + await page.evaluate(async () => { + const controller = new AbortController(); + const pending = fetch('/slow', { signal: controller.signal }).catch(() => {}); + setTimeout(() => controller.abort(), 200); + await pending; + }); + await page.waitForTimeout(300); + expect(reported.length).toBeGreaterThan(0); + expect(recorder.signals.filter((s) => s.kind === 'requestfailed')).toEqual([]); + } finally { + await instance.close(); + } + }); +}); diff --git a/test/helpers/server.ts b/test/helpers/server.ts index 2e84db1..78a292c 100644 --- a/test/helpers/server.ts +++ b/test/helpers/server.ts @@ -98,6 +98,14 @@ export async function startServer(): Promise { ); return; } + // Answers late, so a page can cancel the request while it is in flight. + if (url === '/slow') { + setTimeout(() => { + res.writeHead(200, { 'content-type': 'text/plain' }); + res.end('late'); + }, 1_500); + return; + } res.writeHead(404, { 'content-type': 'text/plain' }); res.end('not found'); });