diff --git a/.github/actions/find/README.md b/.github/actions/find/README.md index 651babf8..466f1c13 100644 --- a/.github/actions/find/README.md +++ b/.github/actions/find/README.md @@ -43,6 +43,11 @@ configuration option. **Optional** Bool - whether to capture screenshots of scanned pages and include links to them in the issue +#### `timeout_per_url` + +**Optional** Maximum time, in seconds, for one URL. Default: `300`. A timeout or failure stops the action without +filing issues or updating cached results. + #### `scans` **Optional** Stringified JSON array of scans to perform. Core engines and local plugins use string names. @@ -56,6 +61,7 @@ will be performed. See [the plugin docs](../../../PLUGINS.md#loading-plugins-fro Absolute path to a JSON file containing the list of potential accessibility gaps. The action writes this file to a temporary directory and returns the absolute path. For example: `$RUNNER_TEMP/findings-.json`. The file will contain a JSON array of finding objects. For example: + ```json [] ``` diff --git a/.github/actions/find/action.yml b/.github/actions/find/action.yml index 9edff453..de16a563 100644 --- a/.github/actions/find/action.yml +++ b/.github/actions/find/action.yml @@ -29,6 +29,10 @@ inputs: description: 'Whether to ignore HTTPS errors when scanning URLs with self-signed certificates' required: false default: 'false' + timeout_per_url: + description: 'Maximum time in seconds for one URL; defaults to 300' + required: false + default: '300' outputs: findings_file: diff --git a/.github/actions/find/src/findForUrl.ts b/.github/actions/find/src/findForUrl.ts index ebbf0b54..1637c67f 100644 --- a/.github/actions/find/src/findForUrl.ts +++ b/.github/actions/find/src/findForUrl.ts @@ -24,12 +24,18 @@ export async function findForUrl( reducedMotion?: ReducedMotionPreference, colorScheme?: ColorSchemePreference, ignoreHttpsErrors: boolean = false, + browserEndpoint?: string, ): Promise { const {url, excludeSelectors, waitForSelectors} = urlConfig - const browser = await playwright.chromium.launch({ - headless: true, - executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined, - }) + + // Scan processes use the supervisor's browser; direct callers own a new browser. + const browser = browserEndpoint + ? await playwright.chromium.connect(browserEndpoint) + : await playwright.chromium.launch({ + headless: true, + executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined, + }) + const contextOptions = { ...(authContext?.toPlaywrightBrowserContextOptions() ?? {}), ...(reducedMotion ? {reducedMotion} : {}), @@ -47,6 +53,7 @@ export async function findForUrl( ), ) + // Keep collected findings in memory until the complete browser lifecycle succeeds. const findings: Finding[] = [] const addFinding = async (findingData: FindingInput) => { let screenshotId @@ -56,37 +63,36 @@ export async function findForUrl( findings.push({...findingData, screenshotId, originalUrl: url}) } - try { - const scansContext = getScansContext() - - if (scansContext.shouldRunPlugins) { - const plugins = await loadPlugins() - for (const plugin of plugins) { - if (scansContext.scansToPerform.includes(plugin.name)) { - core.info(`Running plugin: ${plugin.name}`) - await invokePlugin({ - plugin, - page, - addFinding, - }) - } else { - core.info(`Skipping plugin ${plugin.name} because it is not included in the 'scans' input`) - } + const scansContext = getScansContext() + + // Run configured plugins before the built-in scanners share the same page. + if (scansContext.shouldRunPlugins) { + const plugins = await loadPlugins() + for (const plugin of plugins) { + if (scansContext.scansToPerform.includes(plugin.name)) { + core.info(`Running plugin: ${plugin.name}`) + await invokePlugin({ + plugin, + page, + addFinding, + }) + } else { + core.info(`Skipping plugin ${plugin.name} because it is not included in the 'scans' input`) } } + } - if (scansContext.shouldPerformAxeScan) { - await runAxeScan({page, addFinding, excludeSelectors}) - } + if (scansContext.shouldPerformAxeScan) { + await runAxeScan({page, addFinding, excludeSelectors}) + } - if (scansContext.shouldPerformAccesslintScan) { - await runAccesslintScan({page, addFinding}) - } - } catch (e) { - core.error(`Error during accessibility scan: ${e}`) + if (scansContext.shouldPerformAccesslintScan) { + await runAccesslintScan({page, addFinding}) } + return findings } finally { + // Close the context first, then ensure the browser is closed even if context cleanup fails. try { await context?.close() } finally { diff --git a/.github/actions/find/src/generateScreenshots.ts b/.github/actions/find/src/generateScreenshots.ts index f1a51aa2..3f79ee3b 100644 --- a/.github/actions/find/src/generateScreenshots.ts +++ b/.github/actions/find/src/generateScreenshots.ts @@ -9,7 +9,6 @@ import * as core from '@actions/core' const SCREENSHOT_DIR = path.join(process.env.GITHUB_WORKSPACE || process.cwd(), '.screenshots') export const generateScreenshots = async function (page: Page) { - let screenshotId: string | undefined // Ensure screenshot directory exists if (!fs.existsSync(SCREENSHOT_DIR)) { fs.mkdirSync(SCREENSHOT_DIR, {recursive: true}) @@ -18,22 +17,17 @@ export const generateScreenshots = async function (page: Page) { core.info(`Using existing screenshot directory ${SCREENSHOT_DIR}`) } - try { - const screenshotBuffer = await page.screenshot({ - fullPage: true, - type: 'png', - }) + const screenshotBuffer = await page.screenshot({ + fullPage: true, + type: 'png', + }) - screenshotId = crypto.randomUUID() - const filename = `${screenshotId}.png` - const filepath = path.join(SCREENSHOT_DIR, filename) + const screenshotId = crypto.randomUUID() + const filename = `${screenshotId}.png` + const filepath = path.join(SCREENSHOT_DIR, filename) - fs.writeFileSync(filepath, screenshotBuffer) - core.info(`Screenshot saved: ${filename}`) - } catch (error) { - core.error(`Failed to capture/save screenshot: ${error}`) - screenshotId = undefined - } + fs.writeFileSync(filepath, screenshotBuffer) + core.info(`Screenshot saved: ${filename}`) return screenshotId } diff --git a/.github/actions/find/src/index.ts b/.github/actions/find/src/index.ts index 836161a2..6f42f427 100644 --- a/.github/actions/find/src/index.ts +++ b/.github/actions/find/src/index.ts @@ -4,33 +4,46 @@ import path from 'node:path' import * as core from '@actions/core' import {AuthContext} from './AuthContext.js' import {findForUrl} from './findForUrl.js' +import {runScanInChildProcess, type ScanRequest, type ScanResponse} from './processSupervisor.js' export default async function () { core.info("Starting 'find' action") + + // Load action inputs before starting any scan process. const urlConfigs = loadUrlConfigs() const urls = loadUrls({urlConfigs}) const reducedMotion = loadReducedMotion() const colorScheme = loadColorScheme() const ignoreHttpsErrors = loadIgnoreHttpsErrors() + const timeoutPerUrl = loadTimeoutPerUrl() const actualUrls = urlConfigs || urls || [] const authContextInput: AuthContextInput = JSON.parse(core.getInput('auth_context', {required: false}) || '{}') - const authContext = new AuthContext(authContextInput) const includeScreenshots = core.getInput('include_screenshots', {required: false}) !== 'false' + // Scan URLs one at a time so only one scan process and browser process group exists. const findings = [] for (const urlConfig of actualUrls) { const {url} = urlConfig core.info(`Preparing to scan ${url}`) - const findingsForUrl = await findForUrl( - urlConfig, - authContext, - includeScreenshots, - reducedMotion, - colorScheme, - ignoreHttpsErrors, - ) + let findingsForUrl + try { + findingsForUrl = await runScanInChildProcess( + { + urlConfig, + authContextInput, + includeScreenshots, + reducedMotion, + colorScheme, + ignoreHttpsErrors, + }, + timeoutPerUrl, + ) + } catch (error) { + throw new Error(`Scan incomplete for ${url}: ${errorMessage(error)}`, {cause: error}) + } + if (findingsForUrl.length === 0) { core.info(`No accessibility gaps were found on ${url}`) continue @@ -39,6 +52,7 @@ export default async function () { core.info(`Found ${findingsForUrl.length} findings for ${url}`) } + // Publish output only after the complete URL set has succeeded. const findingsPath = path.join(process.env.RUNNER_TEMP || '/tmp', `findings-${crypto.randomUUID()}.json`) fs.writeFileSync(findingsPath, JSON.stringify(findings)) core.setOutput('findings_file', findingsPath) @@ -48,6 +62,51 @@ export default async function () { core.info("Finished 'find' action") } +if (process.env.ACCESSIBILITY_SCANNER_SCAN_PROCESS === '1') { + process.once('message', request => { + void processScanRequest(request as ScanRequest) + }) +} + +async function processScanRequest(request: ScanRequest) { + try { + const findings = await findForUrl( + request.urlConfig, + new AuthContext(request.authContextInput), + request.includeScreenshots, + request.reducedMotion, + request.colorScheme, + request.ignoreHttpsErrors, + request.browserEndpoint, + ) + + await sendScanResponse({type: 'result', findings}) + } catch (error) { + process.exitCode = 1 + await sendScanResponse({type: 'error', error: errorMessage(error)}) + } finally { + process.disconnect?.() + } +} + +async function sendScanResponse(response: ScanResponse) { + const send = process.send + if (!send || !process.connected) { + throw new Error('Scan process IPC is unavailable') + } + + await new Promise((resolve, reject) => { + send.call(process, response, error => { + if (error) reject(error) + else resolve() + }) + }) +} + +function errorMessage(error: unknown) { + return error instanceof Error ? error.message : String(error) +} + function loadUrlConfigs() { const urlConfigInput = core.getInput('url_configs', {required: false}) if (!urlConfigInput) return @@ -120,3 +179,12 @@ function loadColorScheme() { function loadIgnoreHttpsErrors() { return core.getInput('ignore_https_errors', {required: false}).toLowerCase() === 'true' } + +function loadTimeoutPerUrl() { + const input = core.getInput('timeout_per_url', {required: false}) || '300' + const seconds = Number(input) + if (!Number.isSafeInteger(seconds) || seconds <= 0 || seconds > 2_147_483) { + throw new Error("Input 'timeout_per_url' must be a positive whole number less than 2,147,484.") + } + return seconds +} diff --git a/.github/actions/find/src/pluginManager/index.ts b/.github/actions/find/src/pluginManager/index.ts index d48009f7..2175a026 100644 --- a/.github/actions/find/src/pluginManager/index.ts +++ b/.github/actions/find/src/pluginManager/index.ts @@ -30,13 +30,14 @@ export async function loadPlugins() { await loadCustomPlugins() await loadNpmPlugins() } - } catch { + } catch (error) { plugins.length = 0 core.error(abortError) + throw error } finally { pluginsLoaded = true - return plugins } + return plugins } export const abortError = ` diff --git a/.github/actions/find/src/processSupervisor.ts b/.github/actions/find/src/processSupervisor.ts new file mode 100644 index 00000000..018e6f76 --- /dev/null +++ b/.github/actions/find/src/processSupervisor.ts @@ -0,0 +1,195 @@ +import {fork} from 'node:child_process' +import {fileURLToPath} from 'node:url' +import playwright from 'playwright' +import type {AuthContextInput, ColorSchemePreference, Finding, ReducedMotionPreference, UrlConfig} from './types.d.js' + +/** Maximum time allowed to stop owned processes and verify their process groups are gone. */ +const PROCESS_CLEANUP_TIMEOUT_MS = 5000 +/** Delay between process-group existence polls during bounded cleanup verification. */ +const PROCESS_GROUP_POLL_INTERVAL_MS = 25 + +export type ScanOptions = { + urlConfig: UrlConfig + authContextInput: AuthContextInput + includeScreenshots: boolean + reducedMotion?: ReducedMotionPreference + colorScheme?: ColorSchemePreference + ignoreHttpsErrors: boolean +} + +export type ScanRequest = ScanOptions & {browserEndpoint: string} + +export type ScanResponse = {type: 'result'; findings: Finding[]} | {type: 'error'; error: string} + +/** + * Runs one URL scan in an isolated process and returns its findings after that process exits successfully. + * @param timeout Maximum scan time in seconds. + */ +export async function runScanInChildProcess(options: ScanOptions, timeout: number): Promise { + const scanCutoffMs = Date.now() + timeout * 1000 + + // The supervisor owns the browser server so one cutoff covers browser startup and scanning. + const browserServer = await playwright.chromium.launchServer({ + headless: true, + executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined, + timeout: Math.max(1, scanCutoffMs - Date.now()), + }) + const browserPid = browserServer.process().pid + if (browserPid === undefined) throw new Error('URL browser process did not start') + + if (Date.now() >= scanCutoffMs) { + await terminateProcessGroups([browserPid], [browserServer.kill()]) + throw new Error('Scan timed out during browser startup') + } + + // A detached scan process lets cleanup terminate the process and any descendants as one group. + let scanProcess + try { + scanProcess = fork(fileURLToPath(new URL('./index.js', import.meta.url)), [], { + detached: true, + execArgv: [], + env: {...process.env, ACCESSIBILITY_SCANNER_SCAN_PROCESS: '1'}, + stdio: ['ignore', 'inherit', 'inherit', 'ipc'], + }) + } catch (error) { + await terminateProcessGroups([browserPid], [browserServer.kill()]) + throw error + } + + let findings: Finding[] | undefined + let exitCode: number | null | undefined + let exitSignal: NodeJS.Signals | null | undefined + + const scanProcessClosed = new Promise(resolve => { + scanProcess.once('close', (code, signal) => { + exitCode = code + exitSignal = signal + resolve() + }) + }) + + // Resolve scan failure from any timeout, process error, or invalid/error IPC message. + let reportScanFailure: (error: Error) => void = () => {} + const scanFailure = new Promise(resolve => (reportScanFailure = resolve)) + scanProcess.on('error', reportScanFailure) + + if (scanProcess.pid === undefined) { + return abortScan([browserPid], scanProcessClosed, new Error('Scan process did not start'), browserServer.kill()) + } + + const scanTimeoutTimer = setTimeout( + () => reportScanFailure(new Error('Scan timed out')), + Math.max(0, scanCutoffMs - Date.now()), + ) + scanProcess.on('message', message => { + if (typeof message !== 'object' || message === null || !('type' in message)) { + reportScanFailure(new Error('Scan process sent an invalid IPC message')) + return + } + + if (message.type === 'result' && 'findings' in message && Array.isArray(message.findings)) { + findings = message.findings + } else if (message.type === 'error' && 'error' in message && typeof message.error === 'string') { + reportScanFailure(new Error(message.error)) + } else { + reportScanFailure(new Error('Scan process sent an invalid IPC message')) + } + }) + + scanProcess.send({...options, browserEndpoint: browserServer.wsEndpoint()}, error => { + if (error) reportScanFailure(error) + }) + + // A clean close is accepted only after the exit state and complete findings response are checked. + const scanError = await Promise.race([scanProcessClosed.then(() => undefined), scanFailure]) + clearTimeout(scanTimeoutTimer) + + const browserClosed = browserServer.kill() + const processGroupPids = [scanProcess.pid, browserPid] + + if (scanError) return abortScan(processGroupPids, scanProcessClosed, scanError, browserClosed) + if (exitCode !== 0 || exitSignal !== null || findings === undefined) { + return abortScan( + processGroupPids, + scanProcessClosed, + new Error(`Scan process exited abnormally (code ${exitCode}, signal ${exitSignal})`), + browserClosed, + ) + } + if (processGroupExists(scanProcess.pid)) { + return abortScan( + processGroupPids, + scanProcessClosed, + new Error('Scan process left descendant processes alive'), + browserClosed, + ) + } + + // The scan process must not leave descendants alive before the browser is stopped normally. + await terminateProcessGroups([browserPid], [browserClosed]) + return findings +} + +/** Force-terminates owned process groups and preserves the original failure after cleanup is verified. */ +export async function abortScan( + processGroupPids: number[], + scanProcessClosed: Promise, + originalError: Error, + browserClosed: Promise = Promise.resolve(), +): Promise { + try { + await terminateProcessGroups(processGroupPids, [scanProcessClosed, browserClosed]) + } catch (cleanupError) { + const message = cleanupError instanceof Error ? cleanupError.message : String(cleanupError) + throw new Error(`${originalError.message}; cleanup could not be verified: ${message}`, {cause: cleanupError}) + } + throw originalError +} + +async function terminateProcessGroups(processGroupPids: number[], shutdownPromises: Promise[]) { + // Give shutdown and process-group disappearance checks one shared cleanup budget. + const cleanupCutoffMs = Date.now() + PROCESS_CLEANUP_TIMEOUT_MS + const uniqueProcessGroupPids = [...new Set(processGroupPids)] + + for (const pid of uniqueProcessGroupPids) { + try { + process.kill(-pid, 'SIGKILL') + } catch (error) { + if (!hasErrorCode(error, 'ESRCH')) throw error + } + } + + // Wait for expected process shutdowns, but retain the cutoff for final OS-level verification. + let shutdownTimer: NodeJS.Timeout | undefined + const shutdownFinished = await Promise.race([ + Promise.all(shutdownPromises).then(() => true), + new Promise(resolve => { + shutdownTimer = setTimeout(() => resolve(false), PROCESS_CLEANUP_TIMEOUT_MS) + }), + ]) + if (shutdownTimer) clearTimeout(shutdownTimer) + + if (!shutdownFinished) throw new Error(`Scan process did not exit within ${PROCESS_CLEANUP_TIMEOUT_MS}ms`) + + for (const pid of uniqueProcessGroupPids) { + while (processGroupExists(pid)) { + const remainingMs = cleanupCutoffMs - Date.now() + if (remainingMs <= 0) throw new Error(`Process group ${pid} is still alive after SIGKILL`) + await new Promise(resolve => setTimeout(resolve, Math.min(PROCESS_GROUP_POLL_INTERVAL_MS, remainingMs))) + } + } +} + +function processGroupExists(pid: number) { + try { + process.kill(-pid, 0) + return true + } catch (error) { + if (hasErrorCode(error, 'ESRCH')) return false + throw error + } +} + +function hasErrorCode(error: unknown, code: string): boolean { + return error instanceof Error && 'code' in error && error.code === code +} diff --git a/.github/actions/find/tests/findForUrl.test.ts b/.github/actions/find/tests/findForUrl.test.ts index 387e2360..81f0bc30 100644 --- a/.github/actions/find/tests/findForUrl.test.ts +++ b/.github/actions/find/tests/findForUrl.test.ts @@ -7,6 +7,7 @@ import axe from 'axe-core' import * as pluginManager from '../src/pluginManager/index.js' import type {Plugin} from '../src/pluginManager/types.js' import {clearCache} from '../src/scansContextProvider.js' +import reflowScan from '../../../scanner-plugins/reflow-scan/index.js' const playwrightMocks = vi.hoisted(() => { const pageGoto = vi.fn() @@ -15,30 +16,42 @@ const playwrightMocks = vi.hoisted(() => { waitFor: locatorWaitFor, })) const pageUrl = vi.fn() + const pageViewportSize = vi.fn() + const pageSetViewportSize = vi.fn() + const pageEvaluate = vi.fn() const contextClose = vi.fn() const browserClose = vi.fn() const contextNewPage = vi.fn(() => ({ goto: pageGoto, locator: pageLocator, url: pageUrl, + viewportSize: pageViewportSize, + setViewportSize: pageSetViewportSize, + evaluate: pageEvaluate, })) const browserNewContext = vi.fn(() => ({ newPage: contextNewPage, close: contextClose, })) - const browserLaunch = vi.fn(() => ({ + const browser = { newContext: browserNewContext, close: browserClose, - })) + } + const browserLaunch = vi.fn(() => browser) + const browserConnect = vi.fn(() => browser) return { browserLaunch, + browserConnect, browserNewContext, contextNewPage, pageGoto, pageLocator, locatorWaitFor, pageUrl, + pageViewportSize, + pageSetViewportSize, + pageEvaluate, contextClose, browserClose, } @@ -54,6 +67,7 @@ vi.mock('playwright', () => ({ default: { chromium: { launch: playwrightMocks.browserLaunch, + connect: playwrightMocks.browserConnect, }, }, })) @@ -99,6 +113,16 @@ describe('findForUrl', () => { } describe('page load handling', () => { + it('connects to a parent-owned browser server when an endpoint is provided', async () => { + actionInput = '' + clearAll() + + await findForUrl({url: 'test.com'}, undefined, false, undefined, undefined, false, 'ws://browser.test') + + expect(playwrightMocks.browserConnect).toHaveBeenCalledWith('ws://browser.test') + expect(playwrightMocks.browserLaunch).not.toHaveBeenCalled() + }) + it('uses the default navigation readiness when no selectors are configured', async () => { actionInput = '' clearAll() @@ -174,15 +198,19 @@ describe('findForUrl', () => { expect(playwrightMocks.browserClose).toHaveBeenCalledTimes(1) }) - it('preserves scan error handling and closes the context and browser', async () => { + it('restores the reflow viewport before propagating the scan error', async () => { const error = new Error('Scan failed') - actionInput = '' + const originalViewport = {width: 1280, height: 720} + actionInput = JSON.stringify(['reflow-scan']) + loadedPlugins = [{name: 'reflow-scan', default: reflowScan}] clearAll() - vi.mocked(AxeBuilder.prototype.analyze).mockRejectedValueOnce(error) + playwrightMocks.pageViewportSize.mockReturnValue(originalViewport) + playwrightMocks.pageEvaluate.mockRejectedValueOnce(error) - await expect(findForUrl({url: 'test.com'})).resolves.toEqual([]) + await expect(findForUrl({url: 'test.com'})).rejects.toBe(error) - expect(core.error).toHaveBeenCalledWith(`Error during accessibility scan: ${error}`) + expect(playwrightMocks.pageSetViewportSize).toHaveBeenNthCalledWith(1, {width: 320, height: 256}) + expect(playwrightMocks.pageSetViewportSize).toHaveBeenNthCalledWith(2, originalViewport) expect(playwrightMocks.contextClose).toHaveBeenCalledTimes(1) expect(playwrightMocks.browserClose).toHaveBeenCalledTimes(1) }) @@ -289,7 +317,7 @@ describe('findForUrl', () => { }) it('runs plugins when a scans entry is an object-form NPM plugin', async () => { - loadedPlugins = [] + loadedPlugins = [{name: 'alt-text-scan', default: vi.fn()}] actionInput = JSON.stringify([ 'axe', { diff --git a/.github/actions/find/tests/fixtures/persistentProcessGroup.mjs b/.github/actions/find/tests/fixtures/persistentProcessGroup.mjs new file mode 100644 index 00000000..b3a7d420 --- /dev/null +++ b/.github/actions/find/tests/fixtures/persistentProcessGroup.mjs @@ -0,0 +1,13 @@ +import {fork} from 'node:child_process' +import {fileURLToPath} from 'node:url' + +if (process.env.PROCESS_GROUP_DESCENDANT === '1') { + process.on('message', () => {}) +} else { + const descendant = fork(fileURLToPath(import.meta.url), [], { + detached: true, + env: {...process.env, PROCESS_GROUP_DESCENDANT: '1'}, + stdio: ['ignore', 'ignore', 'ignore', 'ipc'], + }) + process.send?.([process.pid, descendant.pid]) +} diff --git a/.github/actions/find/tests/index.test.ts b/.github/actions/find/tests/index.test.ts index 13cf72f8..18712fb7 100644 --- a/.github/actions/find/tests/index.test.ts +++ b/.github/actions/find/tests/index.test.ts @@ -3,8 +3,9 @@ import find from '../src/index.js' const mocks = vi.hoisted(() => ({ inputs: {} as Record, - findForUrl: vi.fn(), + runScanInChildProcess: vi.fn(), writeFileSync: vi.fn(), + setOutput: vi.fn(), })) vi.mock('@actions/core', () => ({ @@ -12,7 +13,7 @@ vi.mock('@actions/core', () => ({ getMultilineInput: vi.fn(() => []), debug: vi.fn(), info: vi.fn(), - setOutput: vi.fn(), + setOutput: mocks.setOutput, })) vi.mock('node:fs', () => ({ @@ -21,37 +22,58 @@ vi.mock('node:fs', () => ({ }, })) -vi.mock('../src/findForUrl.js', () => ({ - findForUrl: mocks.findForUrl, +vi.mock('../src/processSupervisor.js', () => ({ + runScanInChildProcess: mocks.runScanInChildProcess, })) -describe('url_configs', () => { +describe('find action', () => { beforeEach(() => { vi.clearAllMocks() for (const name of Object.keys(mocks.inputs)) delete mocks.inputs[name] - mocks.findForUrl.mockResolvedValue([]) + mocks.runScanInChildProcess.mockResolvedValue([]) }) - it('passes waitForSelectors through to the URL scan', async () => { + it('passes the URL configuration and scan options to the scan process', async () => { const urlConfig = { url: 'https://example.com', excludeSelectors: ['iframe'], waitForSelectors: ['#app', '[data-ready]'], } mocks.inputs.url_configs = JSON.stringify([urlConfig]) + mocks.inputs.auth_context = JSON.stringify({username: 'octocat'}) mocks.inputs.include_screenshots = 'false' + mocks.inputs.timeout_per_url = '42' await find() - expect(mocks.findForUrl).toHaveBeenCalledWith(urlConfig, expect.anything(), false, undefined, undefined, false) + expect(mocks.runScanInChildProcess).toHaveBeenCalledWith( + expect.objectContaining({urlConfig, authContextInput: {username: 'octocat'}}), + 42, + ) }) - it('rejects waitForSelectors values that are not arrays of strings', async () => { - mocks.inputs.url_configs = JSON.stringify([{url: 'https://example.com', waitForSelectors: ['#app', 42]}]) + it('fails with the URL and does not start a later process', async () => { + mocks.inputs.url_configs = JSON.stringify([{url: 'https://broken.example'}, {url: 'https://later.example'}]) + let failFirst: ((error: Error) => void) | undefined + mocks.runScanInChildProcess.mockImplementationOnce(() => new Promise((_resolve, reject) => (failFirst = reject))) - await expect(find()).rejects.toThrow( - "Invalid 'url_configs' input: Each 'waitForSelectors' field in 'url_configs' must be an array of CSS selector strings.", + const running = expect(find()).rejects.toThrow( + 'Scan incomplete for https://broken.example: process timed out and cleanup was verified', ) - expect(mocks.findForUrl).not.toHaveBeenCalled() + await vi.waitFor(() => expect(mocks.runScanInChildProcess).toHaveBeenCalledTimes(1)) + failFirst?.(new Error('process timed out and cleanup was verified')) + await running + + expect(mocks.runScanInChildProcess).toHaveBeenCalledTimes(1) + expect(mocks.writeFileSync).not.toHaveBeenCalled() + expect(mocks.setOutput).not.toHaveBeenCalled() + }) + + it("rejects invalid 'timeout_per_url' values", async () => { + mocks.inputs.url_configs = JSON.stringify([{url: 'https://example.com'}]) + mocks.inputs.timeout_per_url = '0' + + await expect(find()).rejects.toThrow("Input 'timeout_per_url' must be a positive whole number") + expect(mocks.runScanInChildProcess).not.toHaveBeenCalled() }) }) diff --git a/.github/actions/find/tests/pluginManager.test.ts b/.github/actions/find/tests/pluginManager.test.ts index 92cd0416..7b39992b 100644 --- a/.github/actions/find/tests/pluginManager.test.ts +++ b/.github/actions/find/tests/pluginManager.test.ts @@ -66,8 +66,8 @@ describe('pluginManager', () => { it('Aborts loading all plugins', async () => { pluginManager.clearCache() const logSpy = vi.spyOn(core, 'error').mockImplementation(() => {}) - const plugins = await pluginManager.loadPlugins() - expect(plugins.length).toBe(0) + await expect(pluginManager.loadPlugins()).rejects.toThrow('test error') + expect(pluginManager.getPlugins()).toHaveLength(0) expect(logSpy).toHaveBeenCalledWith(pluginManager.abortError) }) }) diff --git a/.github/actions/find/tests/processSupervisor.integration.test.ts b/.github/actions/find/tests/processSupervisor.integration.test.ts new file mode 100644 index 00000000..d8656c13 --- /dev/null +++ b/.github/actions/find/tests/processSupervisor.integration.test.ts @@ -0,0 +1,38 @@ +import {fork} from 'node:child_process' +import {once} from 'node:events' +import {fileURLToPath} from 'node:url' +import {expect, it} from 'vitest' +import {abortScan} from '../src/processSupervisor.js' + +it.skipIf(process.platform === 'win32')( + 'terminates a scan process and its detached descendant', + async () => { + const scanProcess = fork(fileURLToPath(new URL('./fixtures/persistentProcessGroup.mjs', import.meta.url)), [], { + detached: true, + stdio: ['ignore', 'inherit', 'inherit', 'ipc'], + }) + const [message] = await once(scanProcess, 'message') + if (!Array.isArray(message) || message.length !== 2 || message.some(pid => typeof pid !== 'number')) { + throw new Error('Fixture returned invalid process IDs') + } + const [scanProcessPid, descendantPid] = message + const scanProcessClosed = once(scanProcess, 'close').then(() => undefined) + + await expect( + abortScan([scanProcessPid, descendantPid], scanProcessClosed, new Error('stopped for test')), + ).rejects.toThrow('stopped for test') + for (const pid of [scanProcessPid, descendantPid]) { + expect(processIsGone(pid)).toBe(true) + } + }, + 10_000, +) + +function processIsGone(pid: number) { + try { + process.kill(pid, 0) + return false + } catch (error) { + return error instanceof Error && 'code' in error && error.code === 'ESRCH' + } +} diff --git a/.github/actions/find/tests/processSupervisor.test.ts b/.github/actions/find/tests/processSupervisor.test.ts new file mode 100644 index 00000000..9cce2599 --- /dev/null +++ b/.github/actions/find/tests/processSupervisor.test.ts @@ -0,0 +1,111 @@ +import {EventEmitter} from 'node:events' +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest' +import {runScanInChildProcess} from '../src/processSupervisor.js' + +const mocks = vi.hoisted(() => ({fork: vi.fn(), launchServer: vi.fn(), killBrowser: vi.fn()})) +vi.mock('node:child_process', () => ({fork: mocks.fork})) +vi.mock('playwright', () => ({default: {chromium: {launchServer: mocks.launchServer}}})) + +const options = { + urlConfig: {url: 'https://example.com'}, + authContextInput: {}, + includeScreenshots: false, + ignoreHttpsErrors: false, +} +const browserPid = 5678 +const missingProcess = () => Object.assign(new Error('no such process'), {code: 'ESRCH'}) + +function createScanProcess() { + const scanProcess = Object.assign(new EventEmitter(), { + pid: 4321, + send: vi.fn((_message: unknown, callback: () => void) => callback()), + }) + mocks.fork.mockReturnValue(scanProcess) + return scanProcess +} + +describe('runScanInChildProcess', () => { + let kill: ReturnType + + beforeEach(() => { + vi.clearAllMocks() + vi.useFakeTimers() + mocks.killBrowser.mockResolvedValue(undefined) + mocks.launchServer.mockResolvedValue({ + wsEndpoint: () => 'ws://browser.test', + process: () => ({pid: browserPid}), + kill: mocks.killBrowser, + }) + kill = vi.spyOn(process, 'kill').mockImplementation((_pid, signal) => { + if (signal === 0) throw missingProcess() + return true + }) + }) + + afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() + }) + + it('returns only complete results and stops the browser group', async () => { + const scanProcess = createScanProcess() + const running = runScanInChildProcess(options, 1) + await Promise.resolve() + scanProcess.emit('message', {type: 'result', findings: [{problemShort: 'issue'}]}) + scanProcess.emit('close', 0, null) + + await expect(running).resolves.toEqual([{problemShort: 'issue'}]) + expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') + }) + + it('cleans up the browser when the scan fails to spawn asynchronously', async () => { + const scanProcess = new EventEmitter() + mocks.fork.mockReturnValue(scanProcess) + const running = runScanInChildProcess(options, 1) + await Promise.resolve() + expect(mocks.killBrowser).toHaveBeenCalledOnce() + scanProcess.emit('error', new Error('spawn EAGAIN')) + scanProcess.emit('close', -1, null) + + await expect(running).rejects.toThrow('Scan process did not start') + expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') + }) + + it.each([ + ['timeout', 'Scan timed out'], + ['abnormal exit', 'Scan process exited abnormally'], + ])('terminates on %s', async (outcome, error) => { + const scanProcess = createScanProcess() + const running = runScanInChildProcess(options, 1) + await Promise.resolve() + const rejection = expect(running).rejects.toThrow(error) + + if (outcome === 'timeout') { + await vi.advanceTimersByTimeAsync(1000) + scanProcess.emit('close', null, 'SIGKILL') + } else { + scanProcess.emit('close', 1, null) + } + await vi.runAllTimersAsync() + + await rejection + expect(kill).toHaveBeenCalledWith(-scanProcess.pid!, 'SIGKILL') + expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') + }) + + it.each([ + [false, 'Scan process did not exit within 5000ms'], + [true, 'Process group 4321 is still alive'], + ])('fails when cleanup cannot finish', async (closes, error) => { + const scanProcess = createScanProcess() + kill.mockImplementation(() => true) + const running = runScanInChildProcess(options, 1) + await Promise.resolve() + const rejection = expect(running).rejects.toThrow(error) + + if (closes) scanProcess.emit('close', 1, null) + await vi.advanceTimersByTimeAsync(6000) + + await rejection + }) +}) diff --git a/.github/scanner-plugins/reflow-scan/index.ts b/.github/scanner-plugins/reflow-scan/index.ts index 7f6a5e31..e0436db1 100644 --- a/.github/scanner-plugins/reflow-scan/index.ts +++ b/.github/scanner-plugins/reflow-scan/index.ts @@ -21,6 +21,7 @@ export default async function reflowScan({page, addFinding} = {}) { } } catch (e) { console.error('Error checking horizontal scroll:', e) + throw e } finally { // Restore original viewport so subsequent scans (e.g. Axe) aren't affected if (originalViewport) { diff --git a/README.md b/README.md index f374ec4c..b325cb19 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,7 @@ Trigger the workflow manually or automatically based on your configuration. The | `reduced_motion` | No | Playwright `reducedMotion` setting for scan contexts. Allowed values: `reduce`, `no-preference` | `reduce` | | `color_scheme` | No | Playwright `colorScheme` setting for scan contexts. Allowed values: `light`, `dark`, `no-preference` | `dark` | | `ignore_https_errors` | No | Whether to ignore HTTPS errors when scanning URLs with self-signed certificates. Default: `false` | `true` | +| `timeout_per_url` | No | Maximum time, in seconds, for one URL. Timeout or failure stops the action without filing issues or updating cached results. Default: `300` | `600` | | `scans` | No | An array of scans (or plugins) to be performed. Built-in engines are `axe` and `accesslint`; any other entry is treated as a plugin name. If not provided, only Axe will be performed. | `'["axe", "accesslint", ...other plugins]'` | | `dry_run` | No | When `true`, scan and log the issues that _would_ be filed without opening, closing, reopening, or assigning any issues — and without writing to the `gh-cache` branch. Useful for safely previewing results. Default: `false` | `true` | | `url_configs` | No | A stringified JSON array of URL config objects. Each object must have a `url` field and may have `excludeSelectors` (selectors to exclude from Axe) and `waitForSelectors` (selectors that must become visible within 30 seconds before scanning). When provided, takes precedence over the `urls` input. | `'[{"url":"https://example.com","excludeSelectors":["iframe","#widget"],"waitForSelectors":["#app"]}]'` | diff --git a/action.yml b/action.yml index 8f305a3a..494be4da 100644 --- a/action.yml +++ b/action.yml @@ -67,6 +67,10 @@ inputs: description: 'Whether to ignore HTTPS errors when scanning URLs with self-signed certificates' required: false default: 'false' + timeout_per_url: + description: 'Maximum time in seconds for one URL; defaults to 300' + required: false + default: '300' scans: description: "Stringified JSON array of scans to perform. Core engines and local plugins use string names. Allowlisted NPM plugins use an object with 'name', 'package', and optional 'version'. If not provided, only Axe will be performed" required: false @@ -139,6 +143,7 @@ runs: reduced_motion: ${{ inputs.reduced_motion }} color_scheme: ${{ inputs.color_scheme }} ignore_https_errors: ${{ inputs.ignore_https_errors }} + timeout_per_url: ${{ inputs.timeout_per_url }} scans: ${{ inputs.scans }} - name: File id: file