diff --git a/.github/actions/find/README.md b/.github/actions/find/README.md index 44854fe..d6a4c29 100644 --- a/.github/actions/find/README.md +++ b/.github/actions/find/README.md @@ -43,6 +43,13 @@ configuration option. **Optional** Bool - whether to capture screenshots of scanned pages and include links to them in the issue +#### `url_timeout_ms` + +**Optional** Positive integer (maximum 2147483647) limiting each URL scan in milliseconds. Default: `120000` (2 minutes). Browser setup, navigation, selectors, plugins, and screenshots share this budget. Cleanup has up to five additional seconds, including forced termination. + +A timed-out URL retains confirmed findings and is reported as incomplete; subsequent URLs use a fresh browser. +If process-tree recovery cannot be confirmed, the action stops instead of scanning further URLs. + #### `scans` **Optional** Stringified JSON array of scans to perform. Core engines and local plugins use string names. diff --git a/.github/actions/find/action.yml b/.github/actions/find/action.yml index 8393181..aeb2dce 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' + url_timeout_ms: + description: 'Maximum time in milliseconds to scan each URL (excluding bounded cleanup)' + required: false + default: '120000' outputs: findings_file: diff --git a/.github/actions/find/src/browserCleanup.ts b/.github/actions/find/src/browserCleanup.ts new file mode 100644 index 0000000..bd53af3 --- /dev/null +++ b/.github/actions/find/src/browserCleanup.ts @@ -0,0 +1,80 @@ +import type playwright from 'playwright' +import {execFile, type ChildProcess} from 'node:child_process' +import * as core from '@actions/core' +import {Deadline} from './deadline.js' + +export async function killServer( + server: playwright.BrowserServer, + safeUrl: string, + platform: NodeJS.Platform = process.platform, +): Promise { + try { + await new Deadline(1000).run(() => server.kill()) + } catch (error) { + core.error(`Accessibility scan browser cleanup failed for ${safeUrl}`) + const child = server.process() + const pid = child.pid + if (platform === 'win32') { + if (!pid || child.exitCode !== null || child.signalCode !== null) { + throw new Error(`Cannot verify cleanup of the browser process tree for ${safeUrl}`) + } + let onExit: () => void = () => {} + const exited = new Promise(resolve => { + onExit = resolve + child.once('exit', onExit) + }) + let taskkill: ChildProcess | undefined + try { + await new Deadline(1000).run( + () => + new Promise((resolve, reject) => { + taskkill = execFile('taskkill', ['/PID', String(pid), '/T', '/F'], error => + error ? reject(error) : resolve(), + ) + }), + ) + if (child.exitCode === null && child.signalCode === null) { + await new Deadline(1000).run(() => exited) + } + } catch (killError) { + taskkill?.kill('SIGKILL') + throw new Error(`Cannot verify cleanup of the browser process tree for ${safeUrl}`, {cause: killError}) + } finally { + child.removeListener('exit', onExit) + } + return error + } + if (!pid) throw new Error(`Cannot verify cleanup of the browser process group for ${safeUrl}`) + if (child.exitCode !== null || child.signalCode !== null) { + try { + process.kill(-pid, 'SIGKILL') + } catch (killError) { + if ((killError as NodeJS.ErrnoException).code !== 'ESRCH') { + throw new Error(`Cannot verify cleanup of the browser process group for ${safeUrl}`, {cause: killError}) + } + } + } else { + let onExit: () => void = () => {} + const exited = new Promise(resolve => { + onExit = resolve + child.once('exit', onExit) + }) + try { + process.kill(-pid, 'SIGKILL') + } catch (killError) { + if ((killError as NodeJS.ErrnoException).code !== 'ESRCH') { + child.removeListener('exit', onExit) + throw new Error(`Cannot verify cleanup of the browser process group for ${safeUrl}`, {cause: killError}) + } + } + try { + await new Deadline(1000).run(() => exited) + } catch (waitError) { + throw new Error(`Cannot verify cleanup of the browser process group for ${safeUrl}`, {cause: waitError}) + } finally { + child.removeListener('exit', onExit) + } + } + return error + } +} diff --git a/.github/actions/find/src/deadline.ts b/.github/actions/find/src/deadline.ts new file mode 100644 index 0000000..8ec35dd --- /dev/null +++ b/.github/actions/find/src/deadline.ts @@ -0,0 +1,47 @@ +export class TimeoutError extends Error { + constructor() { + super('URL deadline exceeded') + this.name = 'TimeoutError' + } +} + +export class Deadline { + readonly controller = new AbortController() + private readonly end: number + + constructor(milliseconds: number) { + this.end = performance.now() + milliseconds + } + + remaining() { + return Math.max(0, this.end - performance.now()) + } + + async run(operation: () => Promise): Promise { + const remaining = this.remaining() + if (this.controller.signal.aborted || remaining === 0) { + this.controller.abort() + throw new TimeoutError() + } + + let timer: ReturnType | undefined + try { + const result = await Promise.race([ + Promise.resolve().then(operation), + new Promise((_, reject) => { + timer = setTimeout(() => { + this.controller.abort() + reject(new TimeoutError()) + }, remaining) + }), + ]) + if (this.remaining() === 0) { + this.controller.abort() + throw new TimeoutError() + } + return result + } finally { + clearTimeout(timer) + } + } +} diff --git a/.github/actions/find/src/findForUrl.ts b/.github/actions/find/src/findForUrl.ts index 5ec136b..04779df 100644 --- a/.github/actions/find/src/findForUrl.ts +++ b/.github/actions/find/src/findForUrl.ts @@ -23,6 +23,9 @@ import {sanitizeLabel, sanitizeUrlLabel} from './scanCompletion.js' const SELECTOR_WAIT_TIMEOUT = 30000 +export type ScanProgress = {outcome: UrlScanOutcome; stage: ScanStage; scanner?: string} +type ScanExecution = {endpoint: string; onProgress: (progress: ScanProgress) => void} + export async function findForUrl( urlConfig: UrlConfig, authContext?: AuthContext, @@ -50,6 +53,7 @@ export async function findForUrlWithOutcome( reducedMotion?: ReducedMotionPreference, colorScheme?: ColorSchemePreference, ignoreHttpsErrors: boolean = false, + execution?: ScanExecution, ): Promise { const {findings, scans, failures} = await scanUrlForOutcome( urlConfig, @@ -58,6 +62,7 @@ export async function findForUrlWithOutcome( reducedMotion, colorScheme, ignoreHttpsErrors, + execution, ) return {findings, scans, failures} } @@ -69,22 +74,10 @@ async function scanUrlForOutcome( reducedMotion?: ReducedMotionPreference, colorScheme?: ColorSchemePreference, ignoreHttpsErrors: boolean = false, + execution?: ScanExecution, ): Promise { const {url, excludeSelectors, waitForSelectors} = urlConfig - const scansContext = getScansContext() - const requestedPlugins = [ - ...new Set(scansContext.scansToPerform.filter(name => name !== 'axe' && name !== 'accesslint')), - ] - const scans: ScanCompletion[] = ['axe', 'accesslint', ...requestedPlugins].map(scanner => ({ - requestedUrl: url, - scanner, - status: - (scanner === 'axe' && scansContext.shouldPerformAxeScan) || - (scanner === 'accesslint' && scansContext.shouldPerformAccesslintScan) || - requestedPlugins.includes(scanner) - ? 'not_started' - : 'skipped', - })) + const {scans, requestedPlugins} = planScans(url) const failures: ScanFailure[] = [] const findings: Finding[] = [] @@ -94,26 +87,51 @@ async function scanUrlForOutcome( const safeUrl = sanitizeUrlLabel(url) let stage: ScanStage = 'browser_setup' + let activeScanner: string | undefined let browser: playwright.Browser | undefined let context: playwright.BrowserContext | undefined let page: playwright.Page | undefined let canScan = false let fatalError: unknown + const progress = () => execution?.onProgress({outcome: {findings, scans, failures}, stage, scanner: activeScanner}) + const setStage = (next: ScanStage, scanner?: string) => { + stage = next + activeScanner = scanner + progress() + } - const addFinding = async (findingData: FindingInput) => { - let screenshotId - if (includeScreenshots) { - screenshotId = await generateScreenshots(page!) + const scanWithFindings = async ( + scan: ScanCompletion, + run: (addFinding: (findingData: FindingInput) => Promise) => Promise, + ) => { + let active = true + const addFinding = async (findingData: FindingInput) => { + if (!active) return + const screenshotId = includeScreenshots ? await generateScreenshots(page!, () => active) : undefined + if (!active) return + findings.push({...findingData, screenshotId, originalUrl: url}) + progress() + } + setStage('scan', scan.scanner) + try { + return await runScanner(scan, 'scan', failures, () => run(addFinding)) + } finally { + active = false + activeScanner = undefined + progress() } - findings.push({...findingData, screenshotId, originalUrl: url}) } try { try { - browser = await playwright.chromium.launch({ - headless: true, - executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined, - }) + if (execution) { + browser = await playwright.chromium.connect(execution.endpoint) + } else { + browser = await playwright.chromium.launch({ + headless: true, + executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined, + }) + } const contextOptions = { ...(authContext?.toPlaywrightBrowserContextOptions() ?? {}), ...(reducedMotion ? {reducedMotion} : {}), @@ -123,9 +141,9 @@ async function scanUrlForOutcome( context = await browser.newContext(contextOptions) page = await context.newPage() - stage = 'navigation' + setStage('navigation') await page.goto(url) - stage = 'wait_for_selectors' + setStage('wait_for_selectors') await Promise.all( (waitForSelectors ?? []).map(selector => page!.locator(selector).waitFor({state: 'visible', timeout: SELECTOR_WAIT_TIMEOUT}), @@ -142,42 +160,51 @@ async function scanUrlForOutcome( } } core.error(`Accessibility scan could not start at ${stage} for ${safeUrl}`) + progress() } if (canScan && page) { const pluginScans = scans.filter(scan => requestedPlugins.includes(scan.scanner)) if (pluginScans.length > 0) { let plugins: Plugin[] = [] + setStage('plugin_setup') try { plugins = await loadPlugins() - } catch { + } catch (error) { for (const scan of pluginScans) { - markScanFailure(scan, 'plugin_setup', new Error('plugin setup failed'), failures) + markScanFailure(scan, 'plugin_setup', error, failures) } + progress() } for (const scan of pluginScans) { if (scan.status !== 'not_started') continue const plugin = plugins.find(candidate => candidate.name === scan.scanner) if (!plugin) { markScanFailure(scan, 'plugin_setup', new Error('plugin unavailable'), failures) + progress() continue } core.info(`Running plugin: ${sanitizeLabel(plugin.name)}`) - await runScanner(scan, 'scan', failures, () => invokePlugin({plugin, page: page!, addFinding})) + const unsafePage = await scanWithFindings(scan, addFinding => invokePlugin({plugin, page: page!, addFinding})) + if (unsafePage) { + canScan = false + break + } } } const axeScan = scans.find(scan => scan.scanner === 'axe') - if (axeScan?.status === 'not_started') { - await runScanner(axeScan, 'scan', failures, () => runAxeScan({page: page!, addFinding, excludeSelectors})) + if (canScan && axeScan?.status === 'not_started') { + await scanWithFindings(axeScan, addFinding => runAxeScan({page: page!, addFinding, excludeSelectors})) } const accesslintScan = scans.find(scan => scan.scanner === 'accesslint') - if (accesslintScan?.status === 'not_started') { - await runScanner(accesslintScan, 'scan', failures, () => runAccesslintScan({page: page!, addFinding})) + if (canScan && accesslintScan?.status === 'not_started') { + await scanWithFindings(accesslintScan, addFinding => runAccesslintScan({page: page!, addFinding})) } } } finally { + setStage('cleanup') for (const [resource, close] of [ ['context', () => context?.close()], ['browser', () => browser?.close()], @@ -189,11 +216,30 @@ async function scanUrlForOutcome( failures.push({requestedUrl: url, status, stage: 'cleanup'}) fatalError ??= error core.error(`Accessibility scan cleanup failed for ${safeUrl} (${resource})`) + progress() } } } - return {findings, scans, failures, fatalError} + return {findings: [...findings], scans, failures, fatalError} +} + +export function planScans(url: string) { + const scansContext = getScansContext() + const requestedPlugins = [ + ...new Set(scansContext.scansToPerform.filter(name => name !== 'axe' && name !== 'accesslint')), + ] + const scans: ScanCompletion[] = ['axe', 'accesslint', ...requestedPlugins].map(scanner => ({ + requestedUrl: url, + scanner, + status: + (scanner === 'axe' && scansContext.shouldPerformAxeScan) || + (scanner === 'accesslint' && scansContext.shouldPerformAccesslintScan) || + requestedPlugins.includes(scanner) + ? 'not_started' + : 'skipped', + })) + return {scans, requestedPlugins} } async function runScanner(scan: ScanCompletion, stage: ScanStage, failures: ScanFailure[], run: () => Promise) { @@ -202,7 +248,14 @@ async function runScanner(scan: ScanCompletion, stage: ScanStage, failures: Scan scan.status = 'completed' } catch (error) { markScanFailure(scan, stage, error, failures) + return ( + typeof error === 'object' && + error !== null && + (('pageStateUnsafe' in error && error.pageStateUnsafe === true) || + ('viewportMayBeDirty' in error && error.viewportMayBeDirty === true)) + ) } + return false } function markScanFailure(scan: ScanCompletion, stage: ScanStage, error: unknown, failures: ScanFailure[]) { @@ -215,7 +268,7 @@ function markScanFailure(scan: ScanCompletion, stage: ScanStage, error: unknown, ) } -function getFailureStatus(error: unknown): 'failed' | 'timed_out' { +export function getFailureStatus(error: unknown): 'failed' | 'timed_out' { if ( typeof error === 'object' && error !== null && @@ -225,7 +278,7 @@ function getFailureStatus(error: unknown): 'failed' | 'timed_out' { ) { return 'timed_out' } - if (error instanceof Error && /\btimeout\b/i.test(error.message)) return 'timed_out' + if (error instanceof Error && /\b(?:timeout|timed out)\b/i.test(error.message)) return 'timed_out' return 'failed' } diff --git a/.github/actions/find/src/generateScreenshots.ts b/.github/actions/find/src/generateScreenshots.ts index f1a51aa..e8411a6 100644 --- a/.github/actions/find/src/generateScreenshots.ts +++ b/.github/actions/find/src/generateScreenshots.ts @@ -6,9 +6,10 @@ import * as core from '@actions/core' // Use GITHUB_WORKSPACE to ensure screenshots are saved in the workflow workspace root // where the artifact upload step can find them -const SCREENSHOT_DIR = path.join(process.env.GITHUB_WORKSPACE || process.cwd(), '.screenshots') +const SCREENSHOT_DIR = + process.env.SCANNER_SCREENSHOT_DIR || path.join(process.env.GITHUB_WORKSPACE || process.cwd(), '.screenshots') -export const generateScreenshots = async function (page: Page) { +export const generateScreenshots = async function (page: Page, shouldSave: () => boolean = () => true) { let screenshotId: string | undefined // Ensure screenshot directory exists if (!fs.existsSync(SCREENSHOT_DIR)) { @@ -23,6 +24,7 @@ export const generateScreenshots = async function (page: Page) { fullPage: true, type: 'png', }) + if (!shouldSave()) return undefined screenshotId = crypto.randomUUID() const filename = `${screenshotId}.png` diff --git a/.github/actions/find/src/index.ts b/.github/actions/find/src/index.ts index 8cf9d6f..0c22a8f 100644 --- a/.github/actions/find/src/index.ts +++ b/.github/actions/find/src/index.ts @@ -3,7 +3,7 @@ import fs from 'node:fs' import path from 'node:path' import * as core from '@actions/core' import {AuthContext} from './AuthContext.js' -import {findForUrlWithOutcome} from './findForUrl.js' +import {superviseUrl} from './superviseUrl.js' import {createScanCompletionReport, sanitizeUrlLabel, summarizeScanCompletion} from './scanCompletion.js' import type {ScanCompletion, ScanFailure} from './types.js' @@ -14,6 +14,7 @@ export default async function () { const reducedMotion = loadReducedMotion() const colorScheme = loadColorScheme() const ignoreHttpsErrors = loadIgnoreHttpsErrors() + const urlTimeoutMs = loadUrlTimeout() const actualUrls = urlConfigs || urls || [] @@ -27,13 +28,14 @@ export default async function () { for (const urlConfig of actualUrls) { const {url} = urlConfig core.info(`Preparing to scan ${sanitizeUrlLabel(url)}`) - const outcome = await findForUrlWithOutcome( + const outcome = await superviseUrl( urlConfig, authContext, includeScreenshots, reducedMotion, colorScheme, ignoreHttpsErrors, + urlTimeoutMs, ) findings.push(...outcome.findings) scans.push(...outcome.scans) @@ -131,3 +133,12 @@ function loadColorScheme() { function loadIgnoreHttpsErrors() { return core.getInput('ignore_https_errors', {required: false}).toLowerCase() === 'true' } + +function loadUrlTimeout() { + const input = core.getInput('url_timeout_ms', {required: false}) || '120000' + const value = Number(input) + if (!/^[0-9]+$/.test(input) || !Number.isSafeInteger(value) || value <= 0 || value > 2147483647) { + throw new Error("Input 'url_timeout_ms' must be a positive integer no greater than 2147483647.") + } + return value +} diff --git a/.github/actions/find/src/scanWorker.ts b/.github/actions/find/src/scanWorker.ts new file mode 100644 index 0000000..5829970 --- /dev/null +++ b/.github/actions/find/src/scanWorker.ts @@ -0,0 +1,44 @@ +import {AuthContext} from './AuthContext.js' +import {findForUrlWithOutcome} from './findForUrl.js' +import type {AuthContextInput, ColorSchemePreference, ReducedMotionPreference, UrlConfig} from './types.js' + +export type WorkerRequest = { + endpoint: string + urlConfig: UrlConfig + authContext?: AuthContextInput + includeScreenshots: boolean + reducedMotion?: ReducedMotionPreference + colorScheme?: ColorSchemePreference + ignoreHttpsErrors: boolean +} + +let started = false +process.on('message', async (request: WorkerRequest) => { + if (started) return + started = true + try { + let findingsSent = 0 + const outcome = await findForUrlWithOutcome( + request.urlConfig, + new AuthContext(request.authContext ?? {}), + request.includeScreenshots, + request.reducedMotion, + request.colorScheme, + request.ignoreHttpsErrors, + { + endpoint: request.endpoint, + onProgress: progress => { + const findings = progress.outcome.findings.slice(findingsSent) + findingsSent = progress.outcome.findings.length + process.send?.({ + type: 'progress', + progress: {...progress, outcome: {...progress.outcome, findings}}, + }) + }, + }, + ) + process.send?.({type: 'result', outcome}) + } catch { + process.send?.({type: 'error'}) + } +}) diff --git a/.github/actions/find/src/superviseUrl.ts b/.github/actions/find/src/superviseUrl.ts new file mode 100644 index 0000000..3bf4d91 --- /dev/null +++ b/.github/actions/find/src/superviseUrl.ts @@ -0,0 +1,225 @@ +import {execFile, fork, type ChildProcess} from 'node:child_process' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import playwright from 'playwright' +import * as core from '@actions/core' +import {AuthContext} from './AuthContext.js' +import {killServer} from './browserCleanup.js' +import {Deadline, TimeoutError} from './deadline.js' +import {getFailureStatus, planScans, type ScanProgress} from './findForUrl.js' +import {sanitizeUrlLabel} from './scanCompletion.js' +import type {WorkerRequest} from './scanWorker.js' +import type {ColorSchemePreference, ReducedMotionPreference, UrlConfig, UrlScanOutcome} from './types.js' + +type WorkerMessage = + | {type: 'progress'; progress: ScanProgress} + | {type: 'result'; outcome: UrlScanOutcome} + | {type: 'error'} + +export async function superviseUrl( + urlConfig: UrlConfig, + authContext: AuthContext, + includeScreenshots: boolean, + reducedMotion: ReducedMotionPreference | undefined, + colorScheme: ColorSchemePreference | undefined, + ignoreHttpsErrors: boolean, + timeoutMs: number, +): Promise { + const {scans} = planScans(urlConfig.url) + let outcome: UrlScanOutcome = {findings: [], scans, failures: []} + if (scans.every(scan => scan.status === 'skipped')) return outcome + + const deadline = new Deadline(timeoutMs) + const safeUrl = sanitizeUrlLabel(urlConfig.url) + let progress: ScanProgress = {outcome, stage: 'browser_setup'} + let server: playwright.BrowserServer | undefined + let pendingLaunch: Promise | undefined + let worker: ChildProcess | undefined + let accepting = true + let screenshotDir: string | undefined + const screenshotRoot = path.join(process.env.GITHUB_WORKSPACE || process.cwd(), '.screenshots') + + try { + if (includeScreenshots) fs.mkdirSync(screenshotRoot, {recursive: true}) + screenshotDir = fs.mkdtempSync(path.join(includeScreenshots ? screenshotRoot : os.tmpdir(), '.accessibility-scan-')) + server = await deadline.run(() => { + pendingLaunch = playwright.chromium.launchServer({ + headless: true, + executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined, + timeout: Math.max(1, deadline.remaining()), + }) + return pendingLaunch + }) + if (deadline.remaining() === 0) throw new TimeoutError() + worker = fork(new URL('../dist/scanWorker.js', import.meta.url), { + env: {...process.env, SCANNER_SCREENSHOT_DIR: screenshotDir}, + execArgv: [], + detached: process.platform !== 'win32', + stdio: ['ignore', 'inherit', 'inherit', 'ipc'], + }) + const request: WorkerRequest = { + endpoint: server.wsEndpoint(), + urlConfig, + authContext, + includeScreenshots, + reducedMotion, + colorScheme, + ignoreHttpsErrors, + } + const result = new Promise((resolve, reject) => { + worker!.on('message', (message: WorkerMessage | null) => { + if (!accepting || deadline.controller.signal.aborted || deadline.remaining() === 0 || !message) return + if (message.type === 'progress') { + const findings = progress.outcome.findings + findings.push(...message.progress.outcome.findings) + progress = {...message.progress, outcome: {...message.progress.outcome, findings}} + } + if (message.type === 'result') resolve(message.outcome) + if (message.type === 'error') reject(new Error('URL worker failed')) + }) + worker!.once('error', reject) + worker!.once('exit', () => reject(new Error('URL worker exited unexpectedly'))) + worker!.send(request, error => { + if (error) reject(error) + }) + }) + void result.catch(() => {}) + outcome = await deadline.run(() => result) + } catch (error) { + outcome = progress.outcome + const status = getFailureStatus(error) + const scan = outcome.scans.find(item => item.scanner === progress.scanner && item.status === 'not_started') + if (scan) { + scan.status = status + scan.stage = progress.stage + } else { + for (const item of outcome.scans) { + if (item.status === 'not_started') item.stage = progress.stage + } + } + outcome.failures.push({ + requestedUrl: urlConfig.url, + status, + stage: progress.stage, + ...(scan ? {scanner: scan.scanner} : {}), + }) + core.error(`Accessibility scan ${status} during ${progress.stage} for ${safeUrl}`) + } finally { + accepting = false + let workerError: unknown + let browserError: unknown + if (worker) { + try { + await stopWorker(worker) + } catch (error) { + workerError = error + core.error(`Could not terminate URL worker for ${safeUrl}: ${String(error)}`) + } + } + if (!server && pendingLaunch) { + try { + server = await new Deadline(1000).run(() => pendingLaunch!) + } catch (error) { + if (error instanceof TimeoutError) { + void pendingLaunch + .then( + lateServer => killServer(lateServer, safeUrl), + () => undefined, + ) + .catch(lateError => core.error(`Could not terminate browser for ${safeUrl}: ${String(lateError)}`)) + browserError = new Error(`Cannot verify browser startup cleanup for ${safeUrl}`) + } + } + } + if (server) { + try { + const error = await killServer(server, safeUrl) + if (error) + outcome.failures.push({requestedUrl: urlConfig.url, status: getFailureStatus(error), stage: 'cleanup'}) + } catch (error) { + browserError = error + } + } + if (workerError) throw workerError + if (screenshotDir) { + try { + const findingsWithScreenshots = outcome.findings.filter(finding => finding.screenshotId) + if (findingsWithScreenshots.length) { + for (const finding of findingsWithScreenshots) { + if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(finding.screenshotId!)) { + throw new Error('Invalid screenshot ID') + } + const filename = `${finding.screenshotId}.png` + fs.renameSync(path.join(screenshotDir, filename), path.join(screenshotRoot, filename)) + } + } + } catch (error) { + core.error(`Accessibility scan screenshot publication failed for ${safeUrl}: ${String(error)}`) + outcome.failures.push({requestedUrl: urlConfig.url, status: 'failed', stage: 'cleanup'}) + } finally { + try { + fs.rmSync(screenshotDir, {recursive: true, force: true}) + } catch (error) { + core.error(`Accessibility scan screenshot cleanup failed for ${safeUrl}: ${String(error)}`) + outcome.failures.push({requestedUrl: urlConfig.url, status: 'failed', stage: 'cleanup'}) + } + } + } + if (browserError) throw browserError + } + return outcome +} + +async function stopWorker(worker: ChildProcess) { + if (worker.exitCode !== null || worker.signalCode !== null) { + if (process.platform === 'win32') { + throw new Error('Cannot verify cleanup of an exited URL worker process tree on Windows') + } + if (worker.pid) { + try { + process.kill(-worker.pid, 'SIGKILL') + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error + } + } + return + } + let onExit: () => void = () => {} + const exited = new Promise(resolve => { + onExit = resolve + worker.once('exit', onExit) + }) + try { + if (!worker.pid) throw new Error('URL worker PID unavailable') + if (process.platform === 'win32') { + let taskkill: ChildProcess | undefined + try { + await new Deadline(1000).run( + () => + new Promise((resolve, reject) => { + taskkill = execFile('taskkill', ['/PID', String(worker.pid), '/T', '/F'], error => + error ? reject(error) : resolve(), + ) + }), + ) + } catch (error) { + taskkill?.kill('SIGKILL') + if (worker.exitCode === null && worker.signalCode === null) { + worker.kill('SIGKILL') + await new Deadline(1000).run(() => exited) + } + throw new Error('Cannot verify cleanup of the URL worker process tree on Windows', {cause: error}) + } + } else { + try { + process.kill(-worker.pid, 'SIGKILL') + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error + } + } + await new Deadline(1000).run(() => exited) + } finally { + worker.removeListener('exit', onExit) + } +} diff --git a/.github/actions/find/tests/browserCleanup.test.ts b/.github/actions/find/tests/browserCleanup.test.ts new file mode 100644 index 0000000..1767592 --- /dev/null +++ b/.github/actions/find/tests/browserCleanup.test.ts @@ -0,0 +1,116 @@ +import {EventEmitter} from 'node:events' +import {describe, expect, it, vi} from 'vitest' +import type playwright from 'playwright' +import {killServer} from '../src/browserCleanup.js' +import {Deadline} from '../src/deadline.js' + +const taskkill = vi.hoisted(() => vi.fn()) +vi.mock('node:child_process', () => ({execFile: taskkill})) + +describe('browser cleanup', () => { + it('clears the deadline timer when work completes', async () => { + vi.useFakeTimers() + try { + await expect(new Deadline(10000).run(async () => 'done')).resolves.toBe('done') + expect(vi.getTimerCount()).toBe(0) + } finally { + vi.useRealTimers() + } + }) + + it('force-kills the owned process when server cleanup hangs', async () => { + const child = Object.assign(new EventEmitter(), {pid: 12345, exitCode: null, signalCode: null}) + const server = { + process: () => child, + kill: () => new Promise(() => {}), + } as playwright.BrowserServer + const kill = vi.spyOn(process, 'kill').mockImplementation(() => { + child.emit('exit') + return true + }) + vi.useFakeTimers() + try { + const cleanup = killServer(server, 'example.com', 'linux') + await vi.advanceTimersByTimeAsync(1000) + expect(await cleanup).toBeInstanceOf(Error) + expect(kill).toHaveBeenCalledWith(-12345, 'SIGKILL') + expect(vi.getTimerCount()).toBe(0) + } finally { + kill.mockRestore() + vi.useRealTimers() + } + }) + + it('uses taskkill for the Windows browser tree', async () => { + const child = Object.assign(new EventEmitter(), { + pid: 12345, + exitCode: null, + signalCode: null as NodeJS.Signals | null, + }) + + const server = { + process: () => child, + kill: () => Promise.reject(new Error('close failed')), + } as playwright.BrowserServer + taskkill.mockImplementation((_command, _args, callback) => { + queueMicrotask(() => { + child.signalCode = 'SIGKILL' + child.emit('exit') + callback(null) + }) + return {kill: vi.fn()} + }) + expect(await killServer(server, 'example.com', 'win32')).toBeInstanceOf(Error) + expect(taskkill).toHaveBeenCalledWith('taskkill', ['/PID', '12345', '/T', '/F'], expect.any(Function)) + }) + + it('refuses continuation when Windows browser-tree termination fails', async () => { + const child = Object.assign(new EventEmitter(), {pid: 12345, exitCode: null, signalCode: null}) + const server = { + process: () => child, + kill: () => Promise.reject(new Error('close failed')), + } as playwright.BrowserServer + taskkill.mockImplementation((_command, _args, callback) => { + queueMicrotask(() => callback(new Error('taskkill failed'))) + return {kill: vi.fn()} + }) + await expect(killServer(server, 'example.com', 'win32')).rejects.toThrow( + 'Cannot verify cleanup of the browser process tree', + ) + }) + + it('refuses continuation when POSIX process-group termination fails', async () => { + const child = Object.assign(new EventEmitter(), {pid: 12345, exitCode: null, signalCode: null}) + const server = { + process: () => child, + kill: () => Promise.reject(new Error('close failed')), + } as playwright.BrowserServer + const kill = vi.spyOn(process, 'kill').mockImplementation(() => { + throw Object.assign(new Error('permission denied'), {code: 'EPERM'}) + }) + try { + await expect(killServer(server, 'example.com', 'linux')).rejects.toThrow( + 'Cannot verify cleanup of the browser process group', + ) + expect(kill).toHaveBeenCalledOnce() + expect(kill).toHaveBeenCalledWith(-12345, 'SIGKILL') + } finally { + kill.mockRestore() + } + }) + + it('terminates the browser group without waiting when its leader has exited', async () => { + const child = Object.assign(new EventEmitter(), {pid: 12345, exitCode: 1, signalCode: null}) + const server = { + process: () => child, + kill: () => Promise.reject(new Error('close failed')), + } as playwright.BrowserServer + const kill = vi.spyOn(process, 'kill').mockReturnValue(true) + try { + expect(await killServer(server, 'example.com', 'linux')).toBeInstanceOf(Error) + expect(kill).toHaveBeenCalledWith(-12345, 'SIGKILL') + } finally { + kill.mockRestore() + } + }) +}) diff --git a/.github/actions/find/tests/deadline.integration.test.ts b/.github/actions/find/tests/deadline.integration.test.ts new file mode 100644 index 0000000..1460cc5 --- /dev/null +++ b/.github/actions/find/tests/deadline.integration.test.ts @@ -0,0 +1,187 @@ +import {execFileSync, spawn} from 'node:child_process' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import {pathToFileURL} from 'node:url' +import {beforeAll, describe, expect, it, vi} from 'vitest' +import playwright from 'playwright' +import {AuthContext} from '../src/AuthContext.js' +import {findForUrl} from '../src/findForUrl.js' +import {superviseUrl} from '../src/superviseUrl.js' + +const executable = process.env.CI ? '/usr/bin/google-chrome' : playwright.chromium.executablePath() +const root = process.cwd() + +describe.skipIf(process.platform === 'win32' || !fs.existsSync(executable))('process recovery', () => { + beforeAll(() => { + execFileSync(process.execPath, [ + path.join(root, '.github/actions/find/node_modules/typescript/bin/tsc'), + '-p', + path.join(root, '.github/actions/find/tsconfig.json'), + ]) + }) + + it('kills a stopped browser and scans the next URL', async () => { + const launch = playwright.chromium.launchServer.bind(playwright.chromium) + let pid = 0 + const spy = vi.spyOn(playwright.chromium, 'launchServer').mockImplementationOnce(async options => { + const server = await launch(options) + pid = server.process().pid! + process.kill(-pid, 'SIGSTOP') + return server + }) + const started = Date.now() + try { + const failed = await superviseUrl( + {url: 'data:text/html,First'}, + new AuthContext({}), + false, + undefined, + undefined, + false, + 3000, + ) + expect(Date.now() - started).toBeLessThan(8000) + expect(failed.failures.some(failure => failure.status === 'timed_out')).toBe(true) + expect(pid).toBeGreaterThan(0) + expect(() => process.kill(pid, 0)).toThrow() + pid = 0 + + const url = 'data:text/html,Second
Hello
' + const next = await superviseUrl({url}, new AuthContext({}), false, undefined, undefined, false, 10000) + expect(next.scans[0].status).toBe('completed') + expect(next.failures).toEqual([]) + expect(next.findings).toEqual(await findForUrl({url})) + } finally { + spy.mockRestore() + if (pid) { + try { + process.kill(-pid, 'SIGKILL') + } catch { + // The browser has already exited. + } + } + } + }, 20000) + + it.each(['plugin', 'screenshot', 'cleanup', 'exit'])( + 'recovers a stuck worker during %s', + async fault => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'scanner-worker-test-')) + const pluginDir = path.join(dir, '.github/scanner-plugins/hung') + fs.mkdirSync(pluginDir, {recursive: true}) + fs.writeFileSync(path.join(dir, 'package.json'), '{"type":"module"}') + const faults = { + plugin: ` + await addFinding(finding); + const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {stdio: 'ignore'}); + writeFileSync('descendant.pid', String(child.pid)); + setInterval(() => {}, 1000); + while (true) {} + `, + screenshot: 'page.screenshot = () => new Promise(() => {}); await addFinding(finding)', + cleanup: 'page.context().close = () => new Promise(() => {}); return', + exit: ` + const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {stdio: 'ignore'}); + writeFileSync('descendant.pid', String(child.pid)); + process.exit(1); + `, + } + fs.writeFileSync( + path.join(pluginDir, 'index.js'), + ` + import {spawn} from 'node:child_process'; + import {writeFileSync} from 'node:fs'; + export const name = 'hung'; + export default async ({page, addFinding}) => { + const finding = {scannerType: 'hung', url: page.url(), problemShort: 'x', problemUrl: '', solutionShort: ''}; + if (page.url().includes('first')) { ${faults[fault]} } + else await addFinding(finding); + } + `, + ) + const moduleUrl = pathToFileURL(path.join(root, '.github/actions/find/dist/superviseUrl.js')).href + const authUrl = pathToFileURL(path.join(root, '.github/actions/find/dist/AuthContext.js')).href + const script = ` + import {superviseUrl} from ${JSON.stringify(moduleUrl)}; + import {AuthContext} from ${JSON.stringify(authUrl)}; + const scan = (url, timeout) => superviseUrl({url}, new AuthContext({}), true, undefined, undefined, false, timeout); + const start = Date.now(); + const first = await scan('data:text/html,first', 3000); + const firstMs = Date.now() - start; + const next = await scan('data:text/html,second', 10000); + process.send({first, next, firstMs}); + ` + const child = spawn(process.execPath, ['--input-type=module', '-e', script], { + cwd: dir, + env: {...process.env, INPUT_SCANS: '["hung","axe"]', GITHUB_WORKSPACE: dir}, + stdio: ['ignore', 'ignore', 'inherit', 'ipc'], + }) + let result: + | { + first: Awaited> + next: Awaited> + firstMs: number + } + | undefined + child.on('message', message => { + result = message as typeof result + }) + try { + const code = await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + child.kill('SIGTERM') + reject(new Error('Supervisor did not exit after the plugin deadline')) + }, 15000) + child.once('error', error => { + clearTimeout(timer) + reject(error) + }) + child.once('close', exitCode => { + clearTimeout(timer) + resolve(exitCode) + }) + }) + expect(code).toBe(0) + expect(result?.firstMs).toBeLessThan(8000) + if (fault === 'cleanup') { + expect(result?.first.failures).toContainEqual({ + requestedUrl: 'data:text/html,first', + status: 'timed_out', + stage: 'cleanup', + }) + } else if (fault === 'exit') { + expect(result?.first.failures[0].status).toBe('failed') + } else { + expect(result?.first.scans.find(scan => scan.scanner === 'hung')?.status).toBe('timed_out') + expect(result?.first.scans.find(scan => scan.scanner === 'axe')?.status).toBe('not_started') + if (fault === 'screenshot') expect(result?.first.findings).toEqual([]) + if (fault === 'plugin') expect(result?.first.findings).toHaveLength(1) + } + if (fault === 'plugin' || fault === 'exit') { + const pid = Number(fs.readFileSync(path.join(dir, 'descendant.pid'), 'utf8')) + try { + const state = execFileSync('ps', ['-o', 'stat=', '-p', String(pid)], {encoding: 'utf8'}).trim() + expect(state.startsWith('Z')).toBe(true) + } catch (error) { + expect((error as {status?: number}).status).toBe(1) + } + } + expect(result?.next.scans.find(scan => scan.scanner === 'axe')?.status).toBe('completed') + expect(result?.next.failures).toEqual([]) + const screenshot = result?.next.findings.find(finding => finding.scannerType === 'hung')?.screenshotId + expect(screenshot).toBeTruthy() + expect(fs.existsSync(path.join(dir, '.screenshots', `${screenshot}.png`))).toBe(true) + const expectedScreenshots = [...(result?.first.findings ?? []), ...(result?.next.findings ?? [])] + .map(finding => finding.screenshotId) + .filter(Boolean) + expect(fs.readdirSync(path.join(dir, '.screenshots')).sort()).toEqual( + expectedScreenshots.map(id => `${id}.png`).sort(), + ) + } finally { + fs.rmSync(dir, {recursive: true, force: true}) + } + }, + 20000, + ) +}) diff --git a/.github/actions/find/tests/findForUrl.test.ts b/.github/actions/find/tests/findForUrl.test.ts index fbebca9..fc3cdf7 100644 --- a/.github/actions/find/tests/findForUrl.test.ts +++ b/.github/actions/find/tests/findForUrl.test.ts @@ -98,6 +98,42 @@ describe('findForUrl', () => { expect(pluginManager.invokePlugin).toHaveBeenCalledTimes(0) } + it.each([ + ['Viewport restoration failed', 'failed', 'pageStateUnsafe'], + ['reflow-scan resize timed out after 50ms', 'timed_out', 'pageStateUnsafe'], + ['Viewport restoration failed', 'failed', 'viewportMayBeDirty'], + ] as const)('does not run later scanners when a plugin reports "%s"', async (message, status, flag) => { + actionInput = JSON.stringify(['custom', 'axe', 'accesslint']) + clearAll() + loadedPlugins = [ + { + name: 'custom', + default: vi + .fn() + .mockRejectedValue(Object.assign(new Error(message), {name: 'ReflowScanError', [flag]: true, timeoutMs: 50})), + }, + ] + const outcome = await findForUrlWithOutcome({url: 'https://example.com'}) + expect(outcome.scans.find(scan => scan.scanner === 'custom')?.status).toBe(status) + expect(outcome.scans.find(scan => scan.scanner === 'axe')?.status).toBe('not_started') + expect(outcome.scans.find(scan => scan.scanner === 'accesslint')?.status).toBe('not_started') + expect(AxeBuilder.prototype.analyze).not.toHaveBeenCalled() + expect(accesslintAudit).not.toHaveBeenCalled() + }) + + it.each([ + ['navigation', playwrightMocks.pageGoto], + ['wait_for_selectors', playwrightMocks.locatorWaitFor], + ] as const)('continues after a %s failure', async (stage, operation) => { + actionInput = '' + clearAll() + operation.mockRejectedValueOnce(new Error('Readiness failed')) + const first = await findForUrlWithOutcome({url: 'https://one.example', waitForSelectors: ['#app']}) + expect(first.failures[0].stage).toBe(stage) + const next = await findForUrlWithOutcome({url: 'https://two.example'}) + expect(next.scans[0].status).toBe('completed') + }) + describe('page load handling', () => { it('uses the default navigation readiness when no selectors are configured', async () => { actionInput = '' diff --git a/.github/actions/find/tests/index.test.ts b/.github/actions/find/tests/index.test.ts index 4a84620..d9ee413 100644 --- a/.github/actions/find/tests/index.test.ts +++ b/.github/actions/find/tests/index.test.ts @@ -23,8 +23,8 @@ vi.mock('node:fs', () => ({ }, })) -vi.mock('../src/findForUrl.js', () => ({ - findForUrlWithOutcome: mocks.findForUrlWithOutcome, +vi.mock('../src/superviseUrl.js', () => ({ + superviseUrl: mocks.findForUrlWithOutcome, })) describe('url_configs', () => { @@ -61,10 +61,40 @@ describe('url_configs', () => { undefined, undefined, false, + 120000, ) expect(core.setOutput).toHaveBeenCalledWith('scan_complete', 'true') }) + it.each(['0', '-1', '1.5', 'abc', '2147483648'])('rejects invalid URL deadline %s', async timeout => { + mocks.inputs.url_configs = JSON.stringify([{url: 'https://example.com'}]) + mocks.inputs.url_timeout_ms = timeout + await expect(find()).rejects.toThrow("Input 'url_timeout_ms' must be a positive integer") + expect(mocks.findForUrlWithOutcome).not.toHaveBeenCalled() + }) + + it('passes the configured deadline to each URL scan', async () => { + mocks.inputs.url_configs = JSON.stringify([{url: 'https://example.com'}]) + mocks.inputs.url_timeout_ms = '90000' + await find() + expect(mocks.findForUrlWithOutcome).toHaveBeenCalledWith( + {url: 'https://example.com'}, + expect.anything(), + true, + undefined, + undefined, + false, + 90000, + ) + }) + + it('stops when an owned process tree cannot be recovered', async () => { + mocks.inputs.url_configs = JSON.stringify([{url: 'https://one.example'}, {url: 'https://two.example'}]) + mocks.findForUrlWithOutcome.mockRejectedValueOnce(new Error('Cannot verify cleanup')) + await expect(find()).rejects.toThrow('Cannot verify cleanup') + expect(mocks.findForUrlWithOutcome).toHaveBeenCalledTimes(1) + }) + it('rejects waitForSelectors values that are not arrays of strings', async () => { mocks.inputs.url_configs = JSON.stringify([{url: 'https://example.com', waitForSelectors: ['#app', 42]}]) diff --git a/.github/actions/find/tests/superviseUrl.test.ts b/.github/actions/find/tests/superviseUrl.test.ts new file mode 100644 index 0000000..d78423b --- /dev/null +++ b/.github/actions/find/tests/superviseUrl.test.ts @@ -0,0 +1,57 @@ +import {describe, expect, it, vi} from 'vitest' +import {AuthContext} from '../src/AuthContext.js' +import {superviseUrl} from '../src/superviseUrl.js' + +const launchServer = vi.hoisted(() => vi.fn()) +vi.mock('playwright', () => ({default: {chromium: {launchServer}}})) +vi.mock('../src/scansContextProvider.js', () => ({ + getScansContext: () => ({scansToPerform: [], shouldPerformAxeScan: true, shouldPerformAccesslintScan: false}), +})) + +describe('browser startup recovery', () => { + it('stops instead of continuing when launch cleanup cannot be verified', async () => { + vi.useFakeTimers() + launchServer.mockImplementationOnce(() => new Promise(() => {})) + try { + const scan = superviseUrl( + {url: 'https://example.com'}, + new AuthContext({}), + false, + undefined, + undefined, + false, + 100, + ) + const result = expect(scan).rejects.toThrow('Cannot verify browser startup cleanup') + await vi.advanceTimersByTimeAsync(1100) + await result + expect(vi.getTimerCount()).toBe(0) + } finally { + vi.useRealTimers() + } + }) + + it('cleans up a browser returned just after the deadline', async () => { + vi.useFakeTimers() + const kill = vi.fn().mockResolvedValue(undefined) + launchServer.mockImplementationOnce(() => new Promise(resolve => setTimeout(() => resolve({kill}), 120))) + try { + const scan = superviseUrl( + {url: 'https://example.com'}, + new AuthContext({}), + false, + undefined, + undefined, + false, + 100, + ) + await vi.advanceTimersByTimeAsync(120) + const result = await scan + expect(result.failures[0].status).toBe('timed_out') + expect(kill).toHaveBeenCalledOnce() + expect(vi.getTimerCount()).toBe(0) + } finally { + vi.useRealTimers() + } + }) +}) diff --git a/PLUGINS.md b/PLUGINS.md index 7dd702d..259a6e3 100644 --- a/PLUGINS.md +++ b/PLUGINS.md @@ -92,4 +92,5 @@ jobs: ## Things to look out for +- The per-URL deadline cannot cooperatively interrupt synchronous blocking plugin code; it terminates the URL worker instead. - Plugin names should be unique. If multiple plugins have the same name, and the `scans` input array contains this name, all the plugins with that name _will_ run. However, this is not advised because if you want to turn off one plugin, you'll have to go back and change that plugin name. diff --git a/README.md b/README.md index 3da4f9a..1ffa4dd 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` | +| `url_timeout_ms` | No | Per-URL scan deadline in milliseconds, a positive integer up to 2147483647. Default: `120000`; cleanup may take up to 5 additional seconds. | `120000` | | `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 dbeb02b..529ecd0 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' + url_timeout_ms: + description: 'Maximum time in milliseconds to scan each URL (excluding bounded cleanup)' + required: false + default: '120000' 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 @@ -149,6 +153,7 @@ runs: color_scheme: ${{ inputs.color_scheme }} ignore_https_errors: ${{ inputs.ignore_https_errors }} scans: ${{ inputs.scans }} + url_timeout_ms: ${{ inputs.url_timeout_ms }} - name: Stop before filing incomplete scans if: ${{ steps.find.outputs.scan_complete != 'true' }} shell: bash