From fac92b2c5018ccea8f55b1855faf5faa9587c160 Mon Sep 17 00:00:00 2001 From: Clay Miller Date: Thu, 3 Dec 2026 00:06:57 -0500 Subject: [PATCH 1/6] Add scan recovery Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/find/README.md | 6 + .github/actions/find/action.yml | 4 + .github/actions/find/src/findForUrl.ts | 57 +++--- .../actions/find/src/generateScreenshots.ts | 24 +-- .github/actions/find/src/index.ts | 98 +++++++++- .../actions/find/src/pluginManager/index.ts | 7 +- .github/actions/find/src/processSupervisor.ts | 178 ++++++++++++++++++ .github/actions/find/tests/findForUrl.test.ts | 44 ++++- .../tests/fixtures/persistentProcessGroup.mjs | 13 ++ .github/actions/find/tests/index.test.ts | 49 ++++- .../actions/find/tests/pluginManager.test.ts | 4 +- .../processSupervisor.integration.test.ts | 38 ++++ .../find/tests/processSupervisor.test.ts | 98 ++++++++++ .github/scanner-plugins/reflow-scan/index.ts | 1 + README.md | 1 + action.yml | 5 + 16 files changed, 553 insertions(+), 74 deletions(-) create mode 100644 .github/actions/find/src/processSupervisor.ts create mode 100644 .github/actions/find/tests/fixtures/persistentProcessGroup.mjs create mode 100644 .github/actions/find/tests/processSupervisor.integration.test.ts create mode 100644 .github/actions/find/tests/processSupervisor.test.ts 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..dc2c25a3 100644 --- a/.github/actions/find/src/findForUrl.ts +++ b/.github/actions/find/src/findForUrl.ts @@ -24,12 +24,15 @@ 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, - }) + 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 +50,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 +60,36 @@ export async function findForUrl( findings.push({...findingData, screenshotId, originalUrl: url}) } - try { - const scansContext = getScansContext() + 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`) - } + // 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..991fe9b6 100644 --- a/.github/actions/find/src/index.ts +++ b/.github/actions/find/src/index.ts @@ -4,33 +4,44 @@ import path from 'node:path' import * as core from '@actions/core' import {AuthContext} from './AuthContext.js' import {findForUrl} from './findForUrl.js' +import {forkScan, type ChildScanRequest} from './processSupervisor.js' export default async function () { core.info("Starting 'find' action") + // Load action inputs before starting any child 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 child 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 forkScan( + { + 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 +50,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 +60,63 @@ export default async function () { core.info("Finished 'find' action") } +if (process.env.ACCESSIBILITY_SCANNER_SCAN_CHILD === '1') { + process.once('message', request => { + void processScanRequest(request) + }) +} + +async function processScanRequest(request: unknown) { + try { + if (!isChildScanRequest(request)) { + throw new Error('URL scan process received an invalid request') + } + const findings = await findForUrl( + request.urlConfig, + new AuthContext(request.authContextInput), + request.includeScreenshots, + request.reducedMotion, + request.colorScheme, + request.ignoreHttpsErrors, + request.browserEndpoint, + ) + await sendProcessMessage({type: 'result', findings}) + } catch (error) { + process.exitCode = 1 + await sendProcessMessage({type: 'error', error: errorMessage(error)}) + } finally { + process.disconnect?.() + } +} + +async function sendProcessMessage(message: object) { + const send = process.send + if (!send || !process.connected) { + throw new Error('URL scan process IPC is unavailable') + } + await new Promise((resolve, reject) => { + send.call(process, message, error => { + if (error) reject(error) + else resolve() + }) + }) +} + +function isChildScanRequest(request: unknown): request is ChildScanRequest { + if (typeof request !== 'object' || request === null) return false + if (!('urlConfig' in request) || typeof request.urlConfig !== 'object' || request.urlConfig === null) return false + return ( + 'url' in request.urlConfig && + typeof request.urlConfig.url === 'string' && + 'browserEndpoint' in request && + typeof request.browserEndpoint === 'string' + ) +} + +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 @@ -74,7 +143,7 @@ function loadUrlConfigs() { return parsed as UrlConfig[] } catch (e) { - throw new Error(`Invalid 'url_configs' input: ${(e as Error).message}`) + throw new Error(`Invalid 'url_configs' input: ${errorMessage(e)}`) } } @@ -120,3 +189,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 no greater than 2147483.") + } + return seconds +} diff --git a/.github/actions/find/src/pluginManager/index.ts b/.github/actions/find/src/pluginManager/index.ts index d48009f7..9efd751a 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 = ` @@ -180,7 +181,7 @@ export async function loadPluginsFromPath({ } catch (e) { // - log errors here for granular info core.error('error: ') - core.error(e as Error) + core.error(e instanceof Error ? e : String(e)) // - throw error to handle aborting the plugin scans throw e } diff --git a/.github/actions/find/src/processSupervisor.ts b/.github/actions/find/src/processSupervisor.ts new file mode 100644 index 00000000..cf429555 --- /dev/null +++ b/.github/actions/find/src/processSupervisor.ts @@ -0,0 +1,178 @@ +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 terminate owned processes and verify their process groups are gone. */ +const CLEANUP_TIMEOUT_MS = 5000 +/** Delay between process-group existence checks during bounded cleanup verification. */ +const PROCESS_GROUP_CHECK_INTERVAL_MS = 25 + +export type ScanRequest = { + urlConfig: UrlConfig + authContextInput: AuthContextInput + includeScreenshots: boolean + reducedMotion?: ReducedMotionPreference + colorScheme?: ColorSchemePreference + ignoreHttpsErrors: boolean +} + +export type ChildScanRequest = ScanRequest & {browserEndpoint: string} + +/** + * Forks one URL scan and returns only a fully completed result. + * @param timeout Maximum scan time in seconds. + */ +export async function forkScan(request: ScanRequest, timeout: number): Promise { + const deadline = Date.now() + timeout * 1000 + const server = await playwright.chromium.launchServer({ + headless: true, + executablePath: process.env.CI ? '/usr/bin/google-chrome' : undefined, + timeout: Math.max(1, deadline - Date.now()), + }) + const browserPid = server.process().pid + if (browserPid === undefined) throw new Error('URL browser process did not start') + if (Date.now() >= deadline) { + await terminateProcessGroups([browserPid], [server.kill()]) + throw new Error('URL deadline exceeded during browser startup') + } + + let child + try { + child = fork(fileURLToPath(new URL('./index.js', import.meta.url)), [], { + detached: true, + execArgv: [], + env: {...process.env, ACCESSIBILITY_SCANNER_SCAN_CHILD: '1'}, + stdio: ['ignore', 'inherit', 'inherit', 'ipc'], + }) + } catch (error) { + await terminateProcessGroups([browserPid], [server.kill()]) + throw error + } + + let result: Finding[] | undefined + let exitCode: number | null | undefined + let exitSignal: NodeJS.Signals | null | undefined + const closed = new Promise(resolve => { + child.once('close', (code, signal) => { + exitCode = code + exitSignal = signal + resolve() + }) + }) + if (child.pid === undefined) { + return abortScan([browserPid], closed, new Error('URL scan process did not start'), server.kill()) + } + + let fail: (error: Error) => void = () => {} + const failure = new Promise(resolve => (fail = resolve)) + const timer = setTimeout(() => fail(new Error('URL deadline exceeded')), Math.max(0, deadline - Date.now())) + child.on('error', fail) + child.on('message', message => { + if ( + typeof message === 'object' && + message !== null && + 'type' in message && + message.type === 'result' && + 'findings' in message && + Array.isArray(message.findings) + ) { + result = message.findings + } else if ( + typeof message === 'object' && + message !== null && + 'type' in message && + message.type === 'error' && + 'error' in message && + typeof message.error === 'string' + ) { + fail(new Error(message.error)) + } else { + fail(new Error('URL scan process sent an invalid IPC message')) + } + }) + child.send({...request, browserEndpoint: server.wsEndpoint()}, error => { + if (error) fail(error) + }) + + const error = await Promise.race([closed.then(() => undefined), failure]) + clearTimeout(timer) + const browserCleanup = server.kill() + const pids = [child.pid, browserPid] + + if (error) return abortScan(pids, closed, error, browserCleanup) + if (exitCode !== 0 || exitSignal !== null || result === undefined) { + return abortScan( + pids, + closed, + new Error(`URL scan process exited abnormally (code ${exitCode}, signal ${exitSignal})`), + browserCleanup, + ) + } + if (processGroupExists(child.pid)) { + return abortScan(pids, closed, new Error('URL scan process left descendant processes alive'), browserCleanup) + } + + await terminateProcessGroups([browserPid], [browserCleanup]) + return result +} + +/** Force-terminates owned process groups and preserves the original failure after cleanup is verified. */ +export async function abortScan( + processGroupPids: number[], + childClosed: Promise, + originalError: Error, + processCleanup: Promise = Promise.resolve(), +): Promise { + try { + await terminateProcessGroups(processGroupPids, [childClosed, processCleanup]) + } 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[], closers: Promise[]) { + const deadline = Date.now() + CLEANUP_TIMEOUT_MS + const pids = [...new Set(processGroupPids)] + for (const pid of pids) { + try { + process.kill(-pid, 'SIGKILL') + } catch (error) { + if (!hasErrorCode(error, 'ESRCH')) throw error + } + } + + let timer: NodeJS.Timeout | undefined + const closed = await Promise.race([ + Promise.all(closers).then(() => true), + new Promise(resolve => { + timer = setTimeout(() => resolve(false), CLEANUP_TIMEOUT_MS) + }), + ]) + if (timer) clearTimeout(timer) + if (!closed) throw new Error(`URL scan process did not exit within ${CLEANUP_TIMEOUT_MS}ms`) + + for (const pid of pids) { + while (processGroupExists(pid)) { + const remaining = deadline - Date.now() + if (remaining <= 0) throw new Error(`URL process group ${pid} is still alive after SIGKILL`) + await new Promise(resolve => setTimeout(resolve, Math.min(PROCESS_GROUP_CHECK_INTERVAL_MS, remaining))) + } + } +} + +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..f44ab7f1 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(), + forkScan: 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,29 +22,59 @@ vi.mock('node:fs', () => ({ }, })) -vi.mock('../src/findForUrl.js', () => ({ - findForUrl: mocks.findForUrl, +vi.mock('../src/processSupervisor.js', () => ({ + forkScan: mocks.forkScan, })) -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.forkScan.mockResolvedValue([]) }) - it('passes waitForSelectors through to the URL scan', async () => { + it('passes the URL configuration and scan options to the child 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.forkScan).toHaveBeenCalledWith( + expect.objectContaining({urlConfig, authContextInput: {username: 'octocat'}}), + 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.forkScan.mockImplementationOnce(() => new Promise((_resolve, reject) => (failFirst = reject))) + + const running = expect(find()).rejects.toThrow( + 'Scan incomplete for https://broken.example: process timed out and cleanup was verified', + ) + await vi.waitFor(() => expect(mocks.forkScan).toHaveBeenCalledTimes(1)) + failFirst?.(new Error('process timed out and cleanup was verified')) + await running + + expect(mocks.forkScan).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.forkScan).not.toHaveBeenCalled() }) it('rejects waitForSelectors values that are not arrays of strings', async () => { @@ -52,6 +83,6 @@ describe('url_configs', () => { await expect(find()).rejects.toThrow( "Invalid 'url_configs' input: Each 'waitForSelectors' field in 'url_configs' must be an array of CSS selector strings.", ) - expect(mocks.findForUrl).not.toHaveBeenCalled() + expect(mocks.forkScan).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..481de0da --- /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 child and its detached descendant', + async () => { + const child = fork(fileURLToPath(new URL('./fixtures/persistentProcessGroup.mjs', import.meta.url)), [], { + detached: true, + stdio: ['ignore', 'inherit', 'inherit', 'ipc'], + }) + const [message] = await once(child, 'message') + if (!Array.isArray(message) || message.length !== 2 || message.some(pid => typeof pid !== 'number')) { + throw new Error('Fixture returned invalid process IDs') + } + const [childPid, descendantPid] = message + const closed = once(child, 'close').then(() => undefined) + + await expect(abortScan([childPid, descendantPid], closed, new Error('stopped for test'))).rejects.toThrow( + 'stopped for test', + ) + for (const pid of [childPid, 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..418cd9b7 --- /dev/null +++ b/.github/actions/find/tests/processSupervisor.test.ts @@ -0,0 +1,98 @@ +import {EventEmitter} from 'node:events' +import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest' +import {forkScan} 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 request = { + 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 createChild() { + const child = Object.assign(new EventEmitter(), { + pid: 4321, + send: vi.fn((_message: unknown, callback: () => void) => callback()), + }) + mocks.fork.mockReturnValue(child) + return child +} + +describe('forkScan', () => { + 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 child = createChild() + const running = forkScan(request, 1) + await Promise.resolve() + child.emit('message', {type: 'result', findings: [{problemShort: 'issue'}]}) + child.emit('close', 0, null) + + await expect(running).resolves.toEqual([{problemShort: 'issue'}]) + expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') + }) + + it.each([ + ['deadline', 'URL deadline exceeded'], + ['abnormal exit', 'URL scan process exited abnormally'], + ])('terminates on %s', async (outcome, error) => { + const child = createChild() + const running = forkScan(request, 1) + await Promise.resolve() + const rejection = expect(running).rejects.toThrow(error) + + if (outcome === 'deadline') { + await vi.advanceTimersByTimeAsync(1000) + child.emit('close', null, 'SIGKILL') + } else { + child.emit('close', 1, null) + } + await vi.runAllTimersAsync() + + await rejection + expect(kill).toHaveBeenCalledWith(-child.pid!, 'SIGKILL') + expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') + }) + + it.each([ + [false, 'URL scan process did not exit within 5000ms'], + [true, 'process group 4321 is still alive'], + ])('fails when cleanup cannot finish', async (closes, error) => { + const child = createChild() + kill.mockImplementation(() => true) + const running = forkScan(request, 1) + await Promise.resolve() + const rejection = expect(running).rejects.toThrow(error) + + if (closes) child.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 From 3b7086e85f7e1f5a64ae4e289bda6f662c25c376 Mon Sep 17 00:00:00 2001 From: Clay Miller Date: Thu, 3 Dec 2026 00:42:36 -0500 Subject: [PATCH 2/6] Refine scan process naming Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/find/src/index.ts | 32 ++++++------ .../actions/find/src/pluginManager/index.ts | 2 +- .github/actions/find/src/processSupervisor.ts | 49 ++++++++++--------- .github/actions/find/tests/index.test.ts | 20 ++++---- .../processSupervisor.integration.test.ts | 14 +++--- .../find/tests/processSupervisor.test.ts | 42 ++++++++-------- 6 files changed, 82 insertions(+), 77 deletions(-) diff --git a/.github/actions/find/src/index.ts b/.github/actions/find/src/index.ts index 991fe9b6..e4c4fc51 100644 --- a/.github/actions/find/src/index.ts +++ b/.github/actions/find/src/index.ts @@ -4,11 +4,15 @@ import path from 'node:path' import * as core from '@actions/core' import {AuthContext} from './AuthContext.js' import {findForUrl} from './findForUrl.js' -import {forkScan, type ChildScanRequest} from './processSupervisor.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 child process. + // Load action inputs before starting any scan process. const urlConfigs = loadUrlConfigs() const urls = loadUrls({urlConfigs}) const reducedMotion = loadReducedMotion() @@ -21,14 +25,14 @@ export default async function () { const authContextInput: AuthContextInput = JSON.parse(core.getInput('auth_context', {required: false}) || '{}') const includeScreenshots = core.getInput('include_screenshots', {required: false}) !== 'false' - // Scan URLs one at a time so only one child and browser process group exists. + // 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}`) let findingsForUrl try { - findingsForUrl = await forkScan( + findingsForUrl = await runScanInChildProcess( { urlConfig, authContextInput, @@ -68,8 +72,8 @@ if (process.env.ACCESSIBILITY_SCANNER_SCAN_CHILD === '1') { async function processScanRequest(request: unknown) { try { - if (!isChildScanRequest(request)) { - throw new Error('URL scan process received an invalid request') + if (!isScanRequest(request)) { + throw new Error('Scan process received an invalid request') } const findings = await findForUrl( request.urlConfig, @@ -80,29 +84,29 @@ async function processScanRequest(request: unknown) { request.ignoreHttpsErrors, request.browserEndpoint, ) - await sendProcessMessage({type: 'result', findings}) + await sendScanResponse({type: 'result', findings}) } catch (error) { process.exitCode = 1 - await sendProcessMessage({type: 'error', error: errorMessage(error)}) + await sendScanResponse({type: 'error', error: errorMessage(error)}) } finally { process.disconnect?.() } } -async function sendProcessMessage(message: object) { +async function sendScanResponse(response: ScanResponse) { const send = process.send if (!send || !process.connected) { - throw new Error('URL scan process IPC is unavailable') + throw new Error('Scan process IPC is unavailable') } await new Promise((resolve, reject) => { - send.call(process, message, error => { + send.call(process, response, error => { if (error) reject(error) else resolve() }) }) } -function isChildScanRequest(request: unknown): request is ChildScanRequest { +function isScanRequest(request: unknown): request is ScanRequest { if (typeof request !== 'object' || request === null) return false if (!('urlConfig' in request) || typeof request.urlConfig !== 'object' || request.urlConfig === null) return false return ( @@ -143,7 +147,7 @@ function loadUrlConfigs() { return parsed as UrlConfig[] } catch (e) { - throw new Error(`Invalid 'url_configs' input: ${errorMessage(e)}`) + throw new Error(`Invalid 'url_configs' input: ${(e as Error).message}`) } } @@ -194,7 +198,7 @@ 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 no greater than 2147483.") + 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 9efd751a..2175a026 100644 --- a/.github/actions/find/src/pluginManager/index.ts +++ b/.github/actions/find/src/pluginManager/index.ts @@ -181,7 +181,7 @@ export async function loadPluginsFromPath({ } catch (e) { // - log errors here for granular info core.error('error: ') - core.error(e instanceof Error ? e : String(e)) + core.error(e as Error) // - throw error to handle aborting the plugin scans throw e } diff --git a/.github/actions/find/src/processSupervisor.ts b/.github/actions/find/src/processSupervisor.ts index cf429555..b22d404c 100644 --- a/.github/actions/find/src/processSupervisor.ts +++ b/.github/actions/find/src/processSupervisor.ts @@ -8,7 +8,7 @@ const CLEANUP_TIMEOUT_MS = 5000 /** Delay between process-group existence checks during bounded cleanup verification. */ const PROCESS_GROUP_CHECK_INTERVAL_MS = 25 -export type ScanRequest = { +export type ScanOptions = { urlConfig: UrlConfig authContextInput: AuthContextInput includeScreenshots: boolean @@ -17,13 +17,15 @@ export type ScanRequest = { ignoreHttpsErrors: boolean } -export type ChildScanRequest = ScanRequest & {browserEndpoint: string} +export type ScanRequest = ScanOptions & {browserEndpoint: string} + +export type ScanResponse = {type: 'result'; findings: Finding[]} | {type: 'error'; error: string} /** - * Forks one URL scan and returns only a fully completed result. + * Runs one URL scan in a child process and returns only a fully completed result. * @param timeout Maximum scan time in seconds. */ -export async function forkScan(request: ScanRequest, timeout: number): Promise { +export async function runScanInChildProcess(options: ScanOptions, timeout: number): Promise { const deadline = Date.now() + timeout * 1000 const server = await playwright.chromium.launchServer({ headless: true, @@ -37,9 +39,9 @@ export async function forkScan(request: ScanRequest, timeout: number): Promise(resolve => { - child.once('close', (code, signal) => { + scanProcess.once('close', (code, signal) => { exitCode = code exitSignal = signal resolve() }) }) - if (child.pid === undefined) { - return abortScan([browserPid], closed, new Error('URL scan process did not start'), server.kill()) + if (scanProcess.pid === undefined) { + return abortScan([browserPid], closed, new Error('Scan process did not start'), server.kill()) } let fail: (error: Error) => void = () => {} const failure = new Promise(resolve => (fail = resolve)) const timer = setTimeout(() => fail(new Error('URL deadline exceeded')), Math.max(0, deadline - Date.now())) - child.on('error', fail) - child.on('message', message => { + scanProcess.on('error', fail) + scanProcess.on('message', message => { + if (typeof message !== 'object' || message === null || !('type' in message)) { + fail(new Error('Scan process sent an invalid IPC message')) + return + } + if ( - typeof message === 'object' && - message !== null && - 'type' in message && message.type === 'result' && 'findings' in message && Array.isArray(message.findings) ) { result = message.findings } else if ( - typeof message === 'object' && - message !== null && - 'type' in message && message.type === 'error' && 'error' in message && typeof message.error === 'string' ) { fail(new Error(message.error)) } else { - fail(new Error('URL scan process sent an invalid IPC message')) + fail(new Error('Scan process sent an invalid IPC message')) } }) - child.send({...request, browserEndpoint: server.wsEndpoint()}, error => { + scanProcess.send({...options, browserEndpoint: server.wsEndpoint()}, error => { if (error) fail(error) }) const error = await Promise.race([closed.then(() => undefined), failure]) clearTimeout(timer) const browserCleanup = server.kill() - const pids = [child.pid, browserPid] + const pids = [scanProcess.pid, browserPid] if (error) return abortScan(pids, closed, error, browserCleanup) if (exitCode !== 0 || exitSignal !== null || result === undefined) { return abortScan( pids, closed, - new Error(`URL scan process exited abnormally (code ${exitCode}, signal ${exitSignal})`), + new Error(`Scan process exited abnormally (code ${exitCode}, signal ${exitSignal})`), browserCleanup, ) } - if (processGroupExists(child.pid)) { - return abortScan(pids, closed, new Error('URL scan process left descendant processes alive'), browserCleanup) + if (processGroupExists(scanProcess.pid)) { + return abortScan(pids, closed, new Error('Scan process left descendant processes alive'), browserCleanup) } await terminateProcessGroups([browserPid], [browserCleanup]) @@ -152,7 +153,7 @@ async function terminateProcessGroups(processGroupPids: number[], closers: Promi }), ]) if (timer) clearTimeout(timer) - if (!closed) throw new Error(`URL scan process did not exit within ${CLEANUP_TIMEOUT_MS}ms`) + if (!closed) throw new Error(`Scan process did not exit within ${CLEANUP_TIMEOUT_MS}ms`) for (const pid of pids) { while (processGroupExists(pid)) { diff --git a/.github/actions/find/tests/index.test.ts b/.github/actions/find/tests/index.test.ts index f44ab7f1..7149b7dd 100644 --- a/.github/actions/find/tests/index.test.ts +++ b/.github/actions/find/tests/index.test.ts @@ -3,7 +3,7 @@ import find from '../src/index.js' const mocks = vi.hoisted(() => ({ inputs: {} as Record, - forkScan: vi.fn(), + runScanInChildProcess: vi.fn(), writeFileSync: vi.fn(), setOutput: vi.fn(), })) @@ -23,17 +23,17 @@ vi.mock('node:fs', () => ({ })) vi.mock('../src/processSupervisor.js', () => ({ - forkScan: mocks.forkScan, + runScanInChildProcess: mocks.runScanInChildProcess, })) describe('find action', () => { beforeEach(() => { vi.clearAllMocks() for (const name of Object.keys(mocks.inputs)) delete mocks.inputs[name] - mocks.forkScan.mockResolvedValue([]) + mocks.runScanInChildProcess.mockResolvedValue([]) }) - it('passes the URL configuration and scan options to the child process', async () => { + it('passes the URL configuration and scan options to the scan process', async () => { const urlConfig = { url: 'https://example.com', excludeSelectors: ['iframe'], @@ -46,7 +46,7 @@ describe('find action', () => { await find() - expect(mocks.forkScan).toHaveBeenCalledWith( + expect(mocks.runScanInChildProcess).toHaveBeenCalledWith( expect.objectContaining({urlConfig, authContextInput: {username: 'octocat'}}), 42, ) @@ -55,16 +55,16 @@ describe('find action', () => { 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.forkScan.mockImplementationOnce(() => new Promise((_resolve, reject) => (failFirst = reject))) + mocks.runScanInChildProcess.mockImplementationOnce(() => new Promise((_resolve, reject) => (failFirst = reject))) const running = expect(find()).rejects.toThrow( 'Scan incomplete for https://broken.example: process timed out and cleanup was verified', ) - await vi.waitFor(() => expect(mocks.forkScan).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => expect(mocks.runScanInChildProcess).toHaveBeenCalledTimes(1)) failFirst?.(new Error('process timed out and cleanup was verified')) await running - expect(mocks.forkScan).toHaveBeenCalledTimes(1) + expect(mocks.runScanInChildProcess).toHaveBeenCalledTimes(1) expect(mocks.writeFileSync).not.toHaveBeenCalled() expect(mocks.setOutput).not.toHaveBeenCalled() }) @@ -74,7 +74,7 @@ describe('find action', () => { mocks.inputs.timeout_per_url = '0' await expect(find()).rejects.toThrow("Input 'timeout_per_url' must be a positive whole number") - expect(mocks.forkScan).not.toHaveBeenCalled() + expect(mocks.runScanInChildProcess).not.toHaveBeenCalled() }) it('rejects waitForSelectors values that are not arrays of strings', async () => { @@ -83,6 +83,6 @@ describe('find action', () => { await expect(find()).rejects.toThrow( "Invalid 'url_configs' input: Each 'waitForSelectors' field in 'url_configs' must be an array of CSS selector strings.", ) - expect(mocks.forkScan).not.toHaveBeenCalled() + expect(mocks.runScanInChildProcess).not.toHaveBeenCalled() }) }) diff --git a/.github/actions/find/tests/processSupervisor.integration.test.ts b/.github/actions/find/tests/processSupervisor.integration.test.ts index 481de0da..6064e825 100644 --- a/.github/actions/find/tests/processSupervisor.integration.test.ts +++ b/.github/actions/find/tests/processSupervisor.integration.test.ts @@ -5,23 +5,23 @@ import {expect, it} from 'vitest' import {abortScan} from '../src/processSupervisor.js' it.skipIf(process.platform === 'win32')( - 'terminates a child and its detached descendant', + 'terminates a scan process and its detached descendant', async () => { - const child = fork(fileURLToPath(new URL('./fixtures/persistentProcessGroup.mjs', import.meta.url)), [], { + const scanProcess = fork(fileURLToPath(new URL('./fixtures/persistentProcessGroup.mjs', import.meta.url)), [], { detached: true, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], }) - const [message] = await once(child, 'message') + 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 [childPid, descendantPid] = message - const closed = once(child, 'close').then(() => undefined) + const [scanProcessPid, descendantPid] = message + const closed = once(scanProcess, 'close').then(() => undefined) - await expect(abortScan([childPid, descendantPid], closed, new Error('stopped for test'))).rejects.toThrow( + await expect(abortScan([scanProcessPid, descendantPid], closed, new Error('stopped for test'))).rejects.toThrow( 'stopped for test', ) - for (const pid of [childPid, descendantPid]) { + for (const pid of [scanProcessPid, descendantPid]) { expect(processIsGone(pid)).toBe(true) } }, diff --git a/.github/actions/find/tests/processSupervisor.test.ts b/.github/actions/find/tests/processSupervisor.test.ts index 418cd9b7..1e04f815 100644 --- a/.github/actions/find/tests/processSupervisor.test.ts +++ b/.github/actions/find/tests/processSupervisor.test.ts @@ -1,12 +1,12 @@ import {EventEmitter} from 'node:events' import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest' -import {forkScan} from '../src/processSupervisor.js' +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 request = { +const options = { urlConfig: {url: 'https://example.com'}, authContextInput: {}, includeScreenshots: false, @@ -15,16 +15,16 @@ const request = { const browserPid = 5678 const missingProcess = () => Object.assign(new Error('no such process'), {code: 'ESRCH'}) -function createChild() { - const child = Object.assign(new EventEmitter(), { +function createScanProcess() { + const scanProcess = Object.assign(new EventEmitter(), { pid: 4321, send: vi.fn((_message: unknown, callback: () => void) => callback()), }) - mocks.fork.mockReturnValue(child) - return child + mocks.fork.mockReturnValue(scanProcess) + return scanProcess } -describe('forkScan', () => { +describe('runScanInChildProcess', () => { let kill: ReturnType beforeEach(() => { @@ -48,11 +48,11 @@ describe('forkScan', () => { }) it('returns only complete results and stops the browser group', async () => { - const child = createChild() - const running = forkScan(request, 1) + const scanProcess = createScanProcess() + const running = runScanInChildProcess(options, 1) await Promise.resolve() - child.emit('message', {type: 'result', findings: [{problemShort: 'issue'}]}) - child.emit('close', 0, null) + 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') @@ -60,37 +60,37 @@ describe('forkScan', () => { it.each([ ['deadline', 'URL deadline exceeded'], - ['abnormal exit', 'URL scan process exited abnormally'], + ['abnormal exit', 'Scan process exited abnormally'], ])('terminates on %s', async (outcome, error) => { - const child = createChild() - const running = forkScan(request, 1) + const scanProcess = createScanProcess() + const running = runScanInChildProcess(options, 1) await Promise.resolve() const rejection = expect(running).rejects.toThrow(error) if (outcome === 'deadline') { await vi.advanceTimersByTimeAsync(1000) - child.emit('close', null, 'SIGKILL') + scanProcess.emit('close', null, 'SIGKILL') } else { - child.emit('close', 1, null) + scanProcess.emit('close', 1, null) } await vi.runAllTimersAsync() await rejection - expect(kill).toHaveBeenCalledWith(-child.pid!, 'SIGKILL') + expect(kill).toHaveBeenCalledWith(-scanProcess.pid!, 'SIGKILL') expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') }) it.each([ - [false, 'URL scan process did not exit within 5000ms'], + [false, 'Scan process did not exit within 5000ms'], [true, 'process group 4321 is still alive'], ])('fails when cleanup cannot finish', async (closes, error) => { - const child = createChild() + const scanProcess = createScanProcess() kill.mockImplementation(() => true) - const running = forkScan(request, 1) + const running = runScanInChildProcess(options, 1) await Promise.resolve() const rejection = expect(running).rejects.toThrow(error) - if (closes) child.emit('close', 1, null) + if (closes) scanProcess.emit('close', 1, null) await vi.advanceTimersByTimeAsync(6000) await rejection From 8a495f2b669c3567591c480a89102c664c62580b Mon Sep 17 00:00:00 2001 From: Clay Miller Date: Thu, 3 Dec 2026 01:26:12 -0500 Subject: [PATCH 3/6] Simplify scan process supervision Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/find/src/findForUrl.ts | 3 + .github/actions/find/src/index.ts | 24 +--- .github/actions/find/src/processSupervisor.ts | 135 ++++++++++-------- .github/actions/find/tests/index.test.ts | 9 -- .../processSupervisor.integration.test.ts | 8 +- .../find/tests/processSupervisor.test.ts | 14 +- 6 files changed, 98 insertions(+), 95 deletions(-) diff --git a/.github/actions/find/src/findForUrl.ts b/.github/actions/find/src/findForUrl.ts index dc2c25a3..1637c67f 100644 --- a/.github/actions/find/src/findForUrl.ts +++ b/.github/actions/find/src/findForUrl.ts @@ -27,12 +27,15 @@ export async function findForUrl( browserEndpoint?: string, ): Promise { const {url, excludeSelectors, waitForSelectors} = urlConfig + + // 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} : {}), diff --git a/.github/actions/find/src/index.ts b/.github/actions/find/src/index.ts index e4c4fc51..0aa0969d 100644 --- a/.github/actions/find/src/index.ts +++ b/.github/actions/find/src/index.ts @@ -12,6 +12,7 @@ import { export default async function () { core.info("Starting 'find' action") + // Load action inputs before starting any scan process. const urlConfigs = loadUrlConfigs() const urls = loadUrls({urlConfigs}) @@ -46,6 +47,7 @@ export default async function () { } 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 @@ -64,17 +66,14 @@ export default async function () { core.info("Finished 'find' action") } -if (process.env.ACCESSIBILITY_SCANNER_SCAN_CHILD === '1') { +if (process.env.ACCESSIBILITY_SCANNER_SCAN_PROCESS === '1') { process.once('message', request => { - void processScanRequest(request) + void processScanRequest(request as ScanRequest) }) } -async function processScanRequest(request: unknown) { +async function processScanRequest(request: ScanRequest) { try { - if (!isScanRequest(request)) { - throw new Error('Scan process received an invalid request') - } const findings = await findForUrl( request.urlConfig, new AuthContext(request.authContextInput), @@ -84,6 +83,7 @@ async function processScanRequest(request: unknown) { request.ignoreHttpsErrors, request.browserEndpoint, ) + await sendScanResponse({type: 'result', findings}) } catch (error) { process.exitCode = 1 @@ -98,6 +98,7 @@ async function sendScanResponse(response: ScanResponse) { 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) @@ -106,17 +107,6 @@ async function sendScanResponse(response: ScanResponse) { }) } -function isScanRequest(request: unknown): request is ScanRequest { - if (typeof request !== 'object' || request === null) return false - if (!('urlConfig' in request) || typeof request.urlConfig !== 'object' || request.urlConfig === null) return false - return ( - 'url' in request.urlConfig && - typeof request.urlConfig.url === 'string' && - 'browserEndpoint' in request && - typeof request.browserEndpoint === 'string' - ) -} - function errorMessage(error: unknown) { return error instanceof Error ? error.message : String(error) } diff --git a/.github/actions/find/src/processSupervisor.ts b/.github/actions/find/src/processSupervisor.ts index b22d404c..af37e83f 100644 --- a/.github/actions/find/src/processSupervisor.ts +++ b/.github/actions/find/src/processSupervisor.ts @@ -3,10 +3,10 @@ import {fileURLToPath} from 'node:url' import playwright from 'playwright' import type {AuthContextInput, ColorSchemePreference, Finding, ReducedMotionPreference, UrlConfig} from './types.d.js' -/** Maximum time allowed to terminate owned processes and verify their process groups are gone. */ -const CLEANUP_TIMEOUT_MS = 5000 -/** Delay between process-group existence checks during bounded cleanup verification. */ -const PROCESS_GROUP_CHECK_INTERVAL_MS = 25 +/** 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 @@ -22,57 +22,65 @@ export type ScanRequest = ScanOptions & {browserEndpoint: string} export type ScanResponse = {type: 'result'; findings: Finding[]} | {type: 'error'; error: string} /** - * Runs one URL scan in a child process and returns only a fully completed result. + * 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 deadline = Date.now() + timeout * 1000 - const server = await playwright.chromium.launchServer({ + 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, deadline - Date.now()), + timeout: Math.max(1, scanCutoffMs - Date.now()), }) - const browserPid = server.process().pid - if (browserPid === undefined) throw new Error('URL browser process did not start') - if (Date.now() >= deadline) { - await terminateProcessGroups([browserPid], [server.kill()]) - throw new Error('URL deadline exceeded during browser startup') + + if (Date.now() >= scanCutoffMs) { + await 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_CHILD: '1'}, + env: {...process.env, ACCESSIBILITY_SCANNER_SCAN_PROCESS: '1'}, stdio: ['ignore', 'inherit', 'inherit', 'ipc'], }) } catch (error) { - await terminateProcessGroups([browserPid], [server.kill()]) + await browserServer.kill() throw error } - let result: Finding[] | undefined + let findings: Finding[] | undefined let exitCode: number | null | undefined let exitSignal: NodeJS.Signals | null | undefined - const closed = new Promise(resolve => { + + const scanProcessClosed = new Promise(resolve => { scanProcess.once('close', (code, signal) => { exitCode = code exitSignal = signal resolve() }) }) + if (scanProcess.pid === undefined) { - return abortScan([browserPid], closed, new Error('Scan process did not start'), server.kill()) + return abortScan([], scanProcessClosed, new Error('Scan process did not start'), browserServer.kill()) } - let fail: (error: Error) => void = () => {} - const failure = new Promise(resolve => (fail = resolve)) - const timer = setTimeout(() => fail(new Error('URL deadline exceeded')), Math.max(0, deadline - Date.now())) - scanProcess.on('error', fail) + // 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)) + const scanTimeoutTimer = setTimeout( + () => reportScanFailure(new Error('Scan timed out')), + Math.max(0, scanCutoffMs - Date.now()), + ) + scanProcess.on('error', reportScanFailure) scanProcess.on('message', message => { if (typeof message !== 'object' || message === null || !('type' in message)) { - fail(new Error('Scan process sent an invalid IPC message')) + reportScanFailure(new Error('Scan process sent an invalid IPC message')) return } @@ -81,52 +89,61 @@ export async function runScanInChildProcess(options: ScanOptions, timeout: numbe 'findings' in message && Array.isArray(message.findings) ) { - result = message.findings + findings = message.findings } else if ( message.type === 'error' && 'error' in message && typeof message.error === 'string' ) { - fail(new Error(message.error)) + reportScanFailure(new Error(message.error)) } else { - fail(new Error('Scan process sent an invalid IPC message')) + reportScanFailure(new Error('Scan process sent an invalid IPC message')) } }) - scanProcess.send({...options, browserEndpoint: server.wsEndpoint()}, error => { - if (error) fail(error) + + scanProcess.send({...options, browserEndpoint: browserServer.wsEndpoint()}, error => { + if (error) reportScanFailure(error) }) - const error = await Promise.race([closed.then(() => undefined), failure]) - clearTimeout(timer) - const browserCleanup = server.kill() - const pids = [scanProcess.pid, browserPid] + // 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) - if (error) return abortScan(pids, closed, error, browserCleanup) - if (exitCode !== 0 || exitSignal !== null || result === undefined) { + const browserClosed = browserServer.kill() + const processGroupPids = [scanProcess.pid] + + if (scanError) return abortScan(processGroupPids, scanProcessClosed, scanError, browserClosed) + if (exitCode !== 0 || exitSignal !== null || findings === undefined) { return abortScan( - pids, - closed, + processGroupPids, + scanProcessClosed, new Error(`Scan process exited abnormally (code ${exitCode}, signal ${exitSignal})`), - browserCleanup, + browserClosed, ) } if (processGroupExists(scanProcess.pid)) { - return abortScan(pids, closed, new Error('Scan process left descendant processes alive'), browserCleanup) + return abortScan( + processGroupPids, + scanProcessClosed, + new Error('Scan process left descendant processes alive'), + browserClosed, + ) } - await terminateProcessGroups([browserPid], [browserCleanup]) - return result + // The scan process must not leave descendants alive before the browser is stopped normally. + await browserClosed + return findings } /** Force-terminates owned process groups and preserves the original failure after cleanup is verified. */ export async function abortScan( processGroupPids: number[], - childClosed: Promise, + scanProcessClosed: Promise, originalError: Error, - processCleanup: Promise = Promise.resolve(), + browserClosed: Promise = Promise.resolve(), ): Promise { try { - await terminateProcessGroups(processGroupPids, [childClosed, processCleanup]) + 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}) @@ -134,10 +151,12 @@ export async function abortScan( throw originalError } -async function terminateProcessGroups(processGroupPids: number[], closers: Promise[]) { - const deadline = Date.now() + CLEANUP_TIMEOUT_MS - const pids = [...new Set(processGroupPids)] - for (const pid of pids) { +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) { @@ -145,21 +164,23 @@ async function terminateProcessGroups(processGroupPids: number[], closers: Promi } } - let timer: NodeJS.Timeout | undefined - const closed = await Promise.race([ - Promise.all(closers).then(() => true), + // 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 => { - timer = setTimeout(() => resolve(false), CLEANUP_TIMEOUT_MS) + shutdownTimer = setTimeout(() => resolve(false), PROCESS_CLEANUP_TIMEOUT_MS) }), ]) - if (timer) clearTimeout(timer) - if (!closed) throw new Error(`Scan process did not exit within ${CLEANUP_TIMEOUT_MS}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 pids) { + for (const pid of uniqueProcessGroupPids) { while (processGroupExists(pid)) { - const remaining = deadline - Date.now() - if (remaining <= 0) throw new Error(`URL process group ${pid} is still alive after SIGKILL`) - await new Promise(resolve => setTimeout(resolve, Math.min(PROCESS_GROUP_CHECK_INTERVAL_MS, remaining))) + 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))) } } } diff --git a/.github/actions/find/tests/index.test.ts b/.github/actions/find/tests/index.test.ts index 7149b7dd..18712fb7 100644 --- a/.github/actions/find/tests/index.test.ts +++ b/.github/actions/find/tests/index.test.ts @@ -76,13 +76,4 @@ describe('find action', () => { await expect(find()).rejects.toThrow("Input 'timeout_per_url' must be a positive whole number") expect(mocks.runScanInChildProcess).not.toHaveBeenCalled() }) - - it('rejects waitForSelectors values that are not arrays of strings', async () => { - mocks.inputs.url_configs = JSON.stringify([{url: 'https://example.com', waitForSelectors: ['#app', 42]}]) - - await expect(find()).rejects.toThrow( - "Invalid 'url_configs' input: Each 'waitForSelectors' field in 'url_configs' must be an array of CSS selector strings.", - ) - expect(mocks.runScanInChildProcess).not.toHaveBeenCalled() - }) }) diff --git a/.github/actions/find/tests/processSupervisor.integration.test.ts b/.github/actions/find/tests/processSupervisor.integration.test.ts index 6064e825..d8656c13 100644 --- a/.github/actions/find/tests/processSupervisor.integration.test.ts +++ b/.github/actions/find/tests/processSupervisor.integration.test.ts @@ -16,11 +16,11 @@ it.skipIf(process.platform === 'win32')( throw new Error('Fixture returned invalid process IDs') } const [scanProcessPid, descendantPid] = message - const closed = once(scanProcess, 'close').then(() => undefined) + const scanProcessClosed = once(scanProcess, 'close').then(() => undefined) - await expect(abortScan([scanProcessPid, descendantPid], closed, new Error('stopped for test'))).rejects.toThrow( - 'stopped for test', - ) + 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) } diff --git a/.github/actions/find/tests/processSupervisor.test.ts b/.github/actions/find/tests/processSupervisor.test.ts index 1e04f815..e7ea476a 100644 --- a/.github/actions/find/tests/processSupervisor.test.ts +++ b/.github/actions/find/tests/processSupervisor.test.ts @@ -12,7 +12,6 @@ const options = { includeScreenshots: false, ignoreHttpsErrors: false, } -const browserPid = 5678 const missingProcess = () => Object.assign(new Error('no such process'), {code: 'ESRCH'}) function createScanProcess() { @@ -33,7 +32,6 @@ describe('runScanInChildProcess', () => { 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) => { @@ -47,7 +45,7 @@ describe('runScanInChildProcess', () => { vi.restoreAllMocks() }) - it('returns only complete results and stops the browser group', async () => { + it('returns only complete results and stops the browser', async () => { const scanProcess = createScanProcess() const running = runScanInChildProcess(options, 1) await Promise.resolve() @@ -55,11 +53,11 @@ describe('runScanInChildProcess', () => { scanProcess.emit('close', 0, null) await expect(running).resolves.toEqual([{problemShort: 'issue'}]) - expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') + expect(mocks.killBrowser).toHaveBeenCalledTimes(1) }) it.each([ - ['deadline', 'URL deadline exceeded'], + ['timeout', 'Scan timed out'], ['abnormal exit', 'Scan process exited abnormally'], ])('terminates on %s', async (outcome, error) => { const scanProcess = createScanProcess() @@ -67,7 +65,7 @@ describe('runScanInChildProcess', () => { await Promise.resolve() const rejection = expect(running).rejects.toThrow(error) - if (outcome === 'deadline') { + if (outcome === 'timeout') { await vi.advanceTimersByTimeAsync(1000) scanProcess.emit('close', null, 'SIGKILL') } else { @@ -77,12 +75,12 @@ describe('runScanInChildProcess', () => { await rejection expect(kill).toHaveBeenCalledWith(-scanProcess.pid!, 'SIGKILL') - expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') + expect(mocks.killBrowser).toHaveBeenCalledTimes(1) }) it.each([ [false, 'Scan process did not exit within 5000ms'], - [true, 'process group 4321 is still alive'], + [true, 'Process group 4321 is still alive'], ])('fails when cleanup cannot finish', async (closes, error) => { const scanProcess = createScanProcess() kill.mockImplementation(() => true) From fac5ea78305c07382be5b5e3c39d6537198687fc Mon Sep 17 00:00:00 2001 From: Clay Miller Date: Thu, 3 Dec 2026 01:38:39 -0500 Subject: [PATCH 4/6] Fix scan supervisor formatting Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/find/src/index.ts | 6 +----- .github/actions/find/src/processSupervisor.ts | 12 ++---------- 2 files changed, 3 insertions(+), 15 deletions(-) diff --git a/.github/actions/find/src/index.ts b/.github/actions/find/src/index.ts index 0aa0969d..6f42f427 100644 --- a/.github/actions/find/src/index.ts +++ b/.github/actions/find/src/index.ts @@ -4,11 +4,7 @@ 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' +import {runScanInChildProcess, type ScanRequest, type ScanResponse} from './processSupervisor.js' export default async function () { core.info("Starting 'find' action") diff --git a/.github/actions/find/src/processSupervisor.ts b/.github/actions/find/src/processSupervisor.ts index af37e83f..d2c5b5e9 100644 --- a/.github/actions/find/src/processSupervisor.ts +++ b/.github/actions/find/src/processSupervisor.ts @@ -84,17 +84,9 @@ export async function runScanInChildProcess(options: ScanOptions, timeout: numbe return } - if ( - message.type === 'result' && - 'findings' in message && - Array.isArray(message.findings) - ) { + 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' - ) { + } 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')) From 397c0676a04c60558c6479d09f58f6fa85b5c644 Mon Sep 17 00:00:00 2001 From: Clay Miller Date: Thu, 3 Dec 2026 01:58:28 -0500 Subject: [PATCH 5/6] Bound browser process shutdown Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/find/src/processSupervisor.ts | 12 +++++++----- .github/actions/find/tests/processSupervisor.test.ts | 8 +++++--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/.github/actions/find/src/processSupervisor.ts b/.github/actions/find/src/processSupervisor.ts index d2c5b5e9..f30a5b2e 100644 --- a/.github/actions/find/src/processSupervisor.ts +++ b/.github/actions/find/src/processSupervisor.ts @@ -34,9 +34,11 @@ export async function runScanInChildProcess(options: ScanOptions, timeout: numbe 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 browserServer.kill() + await terminateProcessGroups([browserPid], [browserServer.kill()]) throw new Error('Scan timed out during browser startup') } @@ -50,7 +52,7 @@ export async function runScanInChildProcess(options: ScanOptions, timeout: numbe stdio: ['ignore', 'inherit', 'inherit', 'ipc'], }) } catch (error) { - await browserServer.kill() + await terminateProcessGroups([browserPid], [browserServer.kill()]) throw error } @@ -67,7 +69,7 @@ export async function runScanInChildProcess(options: ScanOptions, timeout: numbe }) if (scanProcess.pid === undefined) { - return abortScan([], scanProcessClosed, new Error('Scan process did not start'), browserServer.kill()) + return abortScan([browserPid], scanProcessClosed, new Error('Scan process did not start'), browserServer.kill()) } // Resolve scan failure from any timeout, process error, or invalid/error IPC message. @@ -102,7 +104,7 @@ export async function runScanInChildProcess(options: ScanOptions, timeout: numbe clearTimeout(scanTimeoutTimer) const browserClosed = browserServer.kill() - const processGroupPids = [scanProcess.pid] + const processGroupPids = [scanProcess.pid, browserPid] if (scanError) return abortScan(processGroupPids, scanProcessClosed, scanError, browserClosed) if (exitCode !== 0 || exitSignal !== null || findings === undefined) { @@ -123,7 +125,7 @@ export async function runScanInChildProcess(options: ScanOptions, timeout: numbe } // The scan process must not leave descendants alive before the browser is stopped normally. - await browserClosed + await terminateProcessGroups([browserPid], [browserClosed]) return findings } diff --git a/.github/actions/find/tests/processSupervisor.test.ts b/.github/actions/find/tests/processSupervisor.test.ts index e7ea476a..014c817d 100644 --- a/.github/actions/find/tests/processSupervisor.test.ts +++ b/.github/actions/find/tests/processSupervisor.test.ts @@ -12,6 +12,7 @@ const options = { includeScreenshots: false, ignoreHttpsErrors: false, } +const browserPid = 5678 const missingProcess = () => Object.assign(new Error('no such process'), {code: 'ESRCH'}) function createScanProcess() { @@ -32,6 +33,7 @@ describe('runScanInChildProcess', () => { 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) => { @@ -45,7 +47,7 @@ describe('runScanInChildProcess', () => { vi.restoreAllMocks() }) - it('returns only complete results and stops the browser', async () => { + it('returns only complete results and stops the browser group', async () => { const scanProcess = createScanProcess() const running = runScanInChildProcess(options, 1) await Promise.resolve() @@ -53,7 +55,7 @@ describe('runScanInChildProcess', () => { scanProcess.emit('close', 0, null) await expect(running).resolves.toEqual([{problemShort: 'issue'}]) - expect(mocks.killBrowser).toHaveBeenCalledTimes(1) + expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') }) it.each([ @@ -75,7 +77,7 @@ describe('runScanInChildProcess', () => { await rejection expect(kill).toHaveBeenCalledWith(-scanProcess.pid!, 'SIGKILL') - expect(mocks.killBrowser).toHaveBeenCalledTimes(1) + expect(kill).toHaveBeenCalledWith(-browserPid, 'SIGKILL') }) it.each([ From 9c724d56fcbc5f5e37beae513f980b0b43e44049 Mon Sep 17 00:00:00 2001 From: Clay Miller Date: Fri, 4 Dec 2026 13:05:48 -0500 Subject: [PATCH 6/6] Handle asynchronous scan fork failures Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/actions/find/src/processSupervisor.ts | 9 +++++---- .../actions/find/tests/processSupervisor.test.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/.github/actions/find/src/processSupervisor.ts b/.github/actions/find/src/processSupervisor.ts index f30a5b2e..018e6f76 100644 --- a/.github/actions/find/src/processSupervisor.ts +++ b/.github/actions/find/src/processSupervisor.ts @@ -68,18 +68,19 @@ export async function runScanInChildProcess(options: ScanOptions, timeout: numbe }) }) + // 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()) } - // 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)) const scanTimeoutTimer = setTimeout( () => reportScanFailure(new Error('Scan timed out')), Math.max(0, scanCutoffMs - Date.now()), ) - scanProcess.on('error', reportScanFailure) scanProcess.on('message', message => { if (typeof message !== 'object' || message === null || !('type' in message)) { reportScanFailure(new Error('Scan process sent an invalid IPC message')) diff --git a/.github/actions/find/tests/processSupervisor.test.ts b/.github/actions/find/tests/processSupervisor.test.ts index 014c817d..9cce2599 100644 --- a/.github/actions/find/tests/processSupervisor.test.ts +++ b/.github/actions/find/tests/processSupervisor.test.ts @@ -58,6 +58,19 @@ describe('runScanInChildProcess', () => { 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'],