|
| 1 | +import assert from 'node:assert/strict'; |
| 2 | +import { execFileSync } from 'node:child_process'; |
| 3 | +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; |
| 4 | +import { tmpdir } from 'node:os'; |
| 5 | +import { join } from 'node:path'; |
| 6 | +import test from 'node:test'; |
| 7 | + |
| 8 | +import { GhCliGitHubClient } from '../src/github-client.ts'; |
| 9 | +import type { PullRequest } from '../src/types.ts'; |
| 10 | + |
| 11 | +const pullRequest: PullRequest = { |
| 12 | + id: 'pr-timeout', |
| 13 | + requirementId: 'req-timeout', |
| 14 | + repository: 'acme/widgets', |
| 15 | + number: 81, |
| 16 | + url: 'https://github.com/acme/widgets/pull/81', |
| 17 | + title: 'Timeout recovery', |
| 18 | + baseBranch: 'main', |
| 19 | + headBranch: 'timeout-recovery', |
| 20 | + headSha: 'abc123', |
| 21 | + status: 'open', |
| 22 | + createdAt: '2026-09-21T00:00:00.000Z', |
| 23 | + updatedAt: '2026-09-21T00:00:00.000Z', |
| 24 | +}; |
| 25 | + |
| 26 | +test('GhCliGitHubClient kills a hung gh subprocess at its timeout', async () => { |
| 27 | + const directory = mkdtempSync(join(tmpdir(), 'code-factory-gh-timeout-')); |
| 28 | + const executable = join(directory, 'gh'); |
| 29 | + const pidFile = join(directory, 'pids'); |
| 30 | + const hangTarget = join(directory, 'hung-gh-marker'); |
| 31 | + writeFileSync(hangTarget, ''); |
| 32 | + writeFileSync(executable, [ |
| 33 | + '#!/bin/sh', |
| 34 | + 'if [ "$1" = "api" ]; then printf "[]"; exit 0; fi', |
| 35 | + `printf '%s\\n' "$$" >> '${pidFile.replaceAll("'", "'\\''")}'`, |
| 36 | + `exec tail -f '${hangTarget.replaceAll("'", "'\\''")}'`, |
| 37 | + ].join('\n'), { mode: 0o700 }); |
| 38 | + |
| 39 | + try { |
| 40 | + const client = new GhCliGitHubClient(directory, { executable, timeoutMs: 2_000 }); |
| 41 | + const startedAt = Date.now(); |
| 42 | + await assert.rejects(client.inspectPullRequest(pullRequest), (error: unknown) => { |
| 43 | + assert.ok(error instanceof Error); |
| 44 | + assert.equal(error.name, 'TimeoutError'); |
| 45 | + assert.match(error.message, /^gh (?:pr view|api) timed out after 2000ms$/); |
| 46 | + return true; |
| 47 | + }); |
| 48 | + assert.ok(Date.now() - startedAt < 5_000, 'the hung command should reject promptly'); |
| 49 | + |
| 50 | + assert.ok(existsSync(pidFile), 'the fake gh command should reach its hung state before the timeout'); |
| 51 | + const pids = readPids(pidFile); |
| 52 | + assert.equal(pids.length, 1); |
| 53 | + await waitFor(() => pids.every((pid) => !markedProcessIsRunning(pid, hangTarget))); |
| 54 | + assert.ok(pids.every((pid) => !markedProcessIsRunning(pid, hangTarget)), 'the hung gh subprocess should not be running'); |
| 55 | + } finally { |
| 56 | + for (const pid of existsSync(pidFile) ? readPids(pidFile) : []) { |
| 57 | + if (markedProcessIsRunning(pid, hangTarget)) process.kill(pid, 'SIGKILL'); |
| 58 | + } |
| 59 | + rmSync(directory, { recursive: true, force: true }); |
| 60 | + } |
| 61 | +}); |
| 62 | + |
| 63 | +test('GhCliGitHubClient reports parse failures without copying gh stdout into the error', async () => { |
| 64 | + const directory = mkdtempSync(join(tmpdir(), 'code-factory-gh-parse-')); |
| 65 | + const executable = join(directory, 'gh'); |
| 66 | + writeFileSync(executable, [ |
| 67 | + '#!/usr/bin/env node', |
| 68 | + "process.stdout.write('PRIVATE REVIEW BODY WITH malformed JSON');", |
| 69 | + ].join('\n'), { mode: 0o700 }); |
| 70 | + |
| 71 | + try { |
| 72 | + const client = new GhCliGitHubClient(directory, { executable, timeoutMs: 2_000 }); |
| 73 | + await assert.rejects(client.inspectPullRequest(pullRequest), (error: unknown) => { |
| 74 | + assert.ok(error instanceof SyntaxError); |
| 75 | + assert.match(error.message, /^gh (?:pr view|api) returned invalid JSON$/); |
| 76 | + assert.doesNotMatch(error.message, /PRIVATE REVIEW BODY/); |
| 77 | + return true; |
| 78 | + }); |
| 79 | + } finally { |
| 80 | + rmSync(directory, { recursive: true, force: true }); |
| 81 | + } |
| 82 | +}); |
| 83 | + |
| 84 | +test('GhCliGitHubClient redacts credentials from gh stderr diagnostics', async () => { |
| 85 | + const directory = mkdtempSync(join(tmpdir(), 'code-factory-gh-redaction-')); |
| 86 | + const executable = join(directory, 'gh'); |
| 87 | + const token = 'ghp_abcdefghijklmnopqrstuvwxyz123456'; |
| 88 | + writeFileSync(executable, [ |
| 89 | + '#!/usr/bin/env node', |
| 90 | + `process.stderr.write(${JSON.stringify(`HTTP 401 Authorization: Bearer ${token} https://user:password@github.com`)});`, |
| 91 | + 'process.exitCode = 1;', |
| 92 | + ].join('\n'), { mode: 0o700 }); |
| 93 | + |
| 94 | + try { |
| 95 | + const client = new GhCliGitHubClient(directory, { executable, timeoutMs: 2_000 }); |
| 96 | + await assert.rejects(client.inspectPullRequest(pullRequest), (error: unknown) => { |
| 97 | + assert.ok(error instanceof Error); |
| 98 | + assert.match(error.message, /\[REDACTED\]/); |
| 99 | + assert.doesNotMatch(error.message, new RegExp(token)); |
| 100 | + assert.doesNotMatch(error.message, /user:password/); |
| 101 | + return true; |
| 102 | + }); |
| 103 | + } finally { |
| 104 | + rmSync(directory, { recursive: true, force: true }); |
| 105 | + } |
| 106 | +}); |
| 107 | + |
| 108 | +function readPids(filePath: string): number[] { |
| 109 | + return readFileSync(filePath, 'utf8').trim().split('\n').filter(Boolean).map(Number); |
| 110 | +} |
| 111 | + |
| 112 | +function markedProcessIsRunning(pid: number, marker: string): boolean { |
| 113 | + try { |
| 114 | + const output = execFileSync('ps', ['-o', 'stat=', '-o', 'command=', '-p', String(pid)], { encoding: 'utf8' }).trim(); |
| 115 | + const match = output.match(/^(\S+)\s+(.*)$/s); |
| 116 | + if (!match) return false; |
| 117 | + const [, state, command] = match; |
| 118 | + return !state!.startsWith('Z') && command!.includes(marker); |
| 119 | + } catch { |
| 120 | + return false; |
| 121 | + } |
| 122 | +} |
| 123 | + |
| 124 | +async function waitFor(predicate: () => boolean, timeoutMs = 2_000): Promise<void> { |
| 125 | + const deadline = Date.now() + timeoutMs; |
| 126 | + while (!predicate()) { |
| 127 | + if (Date.now() >= deadline) throw new Error(`Condition was not met within ${timeoutMs}ms`); |
| 128 | + await new Promise<void>((resolve) => setTimeout(resolve, 10)); |
| 129 | + } |
| 130 | +} |
0 commit comments