| 1 | import { appendFileSync, lstatSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; |
| 2 | import { tmpdir } from 'node:os'; |
| 3 | import { join, resolve } from 'node:path'; |
| 4 | import { fileURLToPath } from 'node:url'; |
| 5 | import { spawnSync } from 'node:child_process'; |
| 6 | import { fingerprint, hasRecordedEvidence, issueBody, parseArtifact, renderSummary, repositoryPath } from './findings.mjs'; |
| 7 | import { authorizeRequest, target, validateSnapshot } from './review.mjs'; |
| 8 | |
| 9 | function stop(outcome, reason) { |
| 10 | throw Object.assign(new Error(reason), { outcome, reason }); |
| 11 | } |
| 12 | |
| 13 | export function rightLines(patch) { |
| 14 | const ranges = []; |
| 15 | let oldRemaining = 0; |
| 16 | let newRemaining = 0; |
| 17 | let line = 0; |
| 18 | let hasHunk = false; |
| 19 | for (const entry of (patch || '').split('\n')) { |
| 20 | const hunk = /^@@ -\d+(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(entry); |
| 21 | if (hunk) { |
| 22 | if (oldRemaining || newRemaining) return []; |
| 23 | oldRemaining = Number(hunk[1] ?? 1); |
| 24 | line = Number(hunk[2]); |
| 25 | newRemaining = Number(hunk[3] ?? 1); |
| 26 | if (![oldRemaining, line, newRemaining].every(Number.isSafeInteger)) return []; |
| 27 | hasHunk = true; |
| 28 | continue; |
| 29 | } |
| 30 | if (!hasHunk) continue; |
| 31 | if (entry.startsWith('\\')) continue; |
| 32 | if (!oldRemaining && !newRemaining && entry === '') continue; |
| 33 | if (entry.startsWith('+') && newRemaining > 0) { |
| 34 | ranges.push(line++); |
| 35 | newRemaining--; |
| 36 | } else if (entry.startsWith('-') && oldRemaining > 0) { |
| 37 | oldRemaining--; |
| 38 | } else if (entry.startsWith(' ') && oldRemaining > 0 && newRemaining > 0) { |
| 39 | ranges.push(line++); |
| 40 | oldRemaining--; |
| 41 | newRemaining--; |
| 42 | } else return []; |
| 43 | } |
| 44 | return oldRemaining || newRemaining ? [] : ranges; |
| 45 | } |
| 46 | |
| 47 | export function planPublication(artifact, files, reviews, reviewer) { |
| 48 | const marker = `<!-- codewhale-action-review:v1:${fingerprint([artifact.repository, artifact.pr_number, |
| 49 | artifact.base_sha, artifact.head_sha, artifact.review])} -->`; |
| 50 | const authored = reviews.filter(item => item.user?.login === reviewer && item.state === 'COMMENTED'); |
| 51 | if (authored.some(item => item.body?.includes(marker))) return null; |
| 52 | const known = new Set(authored.flatMap(item => [...(item.body || '').matchAll(/<!-- codewhale-action-finding:v1:([a-f0-9]{64}) -->/g)].map(match => match[1]))); |
| 53 | const byPath = new Map(files.map(file => [file.filename, file])); |
| 54 | const normalized = value => value.trim().replace(/\s+/g, ' ').toLowerCase(); |
| 55 | const selected = []; |
| 56 | const eligible = artifact.review.issues.filter(hasRecordedEvidence); |
| 57 | for (const issue of eligible) { |
| 58 | const file = byPath.get(issue.path); |
| 59 | const id = fingerprint([artifact.repository, artifact.pr_number, issue.path, |
| 60 | file?.sha || artifact.head_sha, issue.line, issue.severity, issue.authorship, |
| 61 | normalized(issue.title), normalized(issue.description)]); |
| 62 | if (!known.has(id)) selected.push({ issue, id, file }); |
| 63 | known.add(id); |
| 64 | } |
| 65 | if (eligible.length && selected.length === 0) return null; |
| 66 | const body = [renderSummary(artifact, selected.map(item => item.issue), eligible.length - selected.length, |
| 67 | artifact.review.issues.length - eligible.length), |
| 68 | marker, ...selected.map(item => `<!-- codewhale-action-finding:v1:${item.id} -->`)].join('\n\n'); |
| 69 | const comments = selected.filter(({ issue, file }) => file && issue.line && issue.inline_anchorable !== false |
| 70 | && issue.authorship === 'introduced' |
| 71 | && rightLines(file.patch).includes(issue.line)).slice(0, 50) |
| 72 | .map(({ issue }) => ({ path: issue.path, line: issue.line, side: 'RIGHT', body: issueBody(issue) })); |
| 73 | if (Buffer.byteLength(body) > 60000 || comments.some(item => Buffer.byteLength(item.body) > 60000)) { |
| 74 | stop('failed', 'review_exceeds_github_limit'); |
| 75 | } |
| 76 | return { commit_id: artifact.head_sha, event: 'COMMENT', body, comments }; |
| 77 | } |
| 78 | |
| 79 | function command(program, args, options) { |
| 80 | return spawnSync(program, args, { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024, |
| 81 | timeout: 120000, killSignal: 'SIGKILL', ...options }); |
| 82 | } |
| 83 | |
| 84 | export function publish(env = process.env, execute = command) { |
| 85 | const root = mkdtempSync(join(env.RUNNER_TEMP || tmpdir(), 'codewhale-publish-')); |
| 86 | const receiptPath = join(root, 'publication.json'); |
| 87 | let receipt = { schema_version: 1, outcome: 'failed', reason: 'setup_failed', publication: 'not_attempted' }; |
| 88 | try { |
| 89 | const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8')); |
| 90 | const { repo, number } = target(env, event); |
| 91 | if (!env.GH_TOKEN) stop('configuration_missing', 'github_token_required'); |
| 92 | const reviewer = env.CW_REVIEWER_LOGIN || 'github-actions[bot]'; |
| 93 | if (!/^[a-zA-Z0-9][a-zA-Z0-9-]{0,99}(?:\[bot\])?$/.test(reviewer)) stop('configuration_missing', 'invalid_reviewer_login'); |
| 94 | const file = lstatSync(env.CW_FINDINGS || ''); |
| 95 | if (!file.isFile() || file.size > 2 * 1024 * 1024) stop('configuration_missing', 'invalid_findings_artifact'); |
| 96 | let artifact; |
| 97 | try { artifact = parseArtifact(readFileSync(env.CW_FINDINGS, 'utf8')); } |
| 98 | catch { stop('configuration_missing', 'invalid_findings_artifact'); } |
| 99 | if (artifact.repository !== repo || artifact.pr_number !== number |
| 100 | || artifact.run_id !== env.GITHUB_RUN_ID || artifact.run_attempt !== env.GITHUB_RUN_ATTEMPT) { |
| 101 | stop('configuration_missing', 'artifact_context_mismatch'); |
| 102 | } |
| 103 | const eligible = artifact.review.issues.filter(hasRecordedEvidence).length; |
| 104 | receipt = { ...receipt, repository: repo, pr_number: number, head_sha: artifact.head_sha, |
| 105 | base_sha: artifact.base_sha, findings: eligible, |
| 106 | withheld_findings: artifact.review.issues.length - eligible }; |
| 107 | const childEnv = Object.fromEntries(['PATH', 'SystemRoot', 'TMPDIR', 'LANG'].filter(key => env[key]).map(key => [key, env[key]])); |
| 108 | Object.assign(childEnv, { HOME: root, GH_CONFIG_DIR: join(root, 'gh'), GH_TOKEN: env.GH_TOKEN, |
| 109 | GH_HOST: 'github.com', GH_PROMPT_DISABLED: '1', NO_COLOR: '1', CI: 'true' }); |
| 110 | const api = (path, paginate = false, input) => { |
| 111 | const args = ['api', path, ...(paginate ? ['--paginate', '--slurp'] : []), |
| 112 | ...(input ? ['--method', 'POST', '--input', '-'] : [])]; |
| 113 | const result = execute('gh', args, { cwd: root, env: childEnv, ...(input ? { input: JSON.stringify(input) } : {}) }); |
| 114 | if (result.status !== 0 || result.error) stop(input ? 'publication_uncertain' : 'failed', |
| 115 | input ? 'inspect_github_before_retry' : 'github_read_failed'); |
| 116 | let data; |
| 117 | try { data = JSON.parse(result.stdout); } |
| 118 | catch { stop(input ? 'publication_uncertain' : 'failed', 'invalid_github_response'); } |
| 119 | if (paginate) { |
| 120 | if (!Array.isArray(data) || data.some(page => !Array.isArray(page))) stop('failed', 'invalid_github_response'); |
| 121 | return data.flat(); |
| 122 | } |
| 123 | return data; |
| 124 | }; |
| 125 | const snapshot = () => { |
| 126 | const pr = api(`repos/${repo}/pulls/${number}`); |
| 127 | validateSnapshot(pr, repo, event, env); |
| 128 | if (pr.head.sha !== artifact.head_sha || pr.base.sha !== artifact.base_sha) stop('superseded', 'revision_changed'); |
| 129 | return pr; |
| 130 | }; |
| 131 | const pr = snapshot(); |
| 132 | authorizeRequest(env, event, repo, number, api); |
| 133 | const files = api(`repos/${repo}/pulls/${number}/files?per_page=100`, true); |
| 134 | if (!Number.isSafeInteger(pr.changed_files) || files.length !== pr.changed_files |
| 135 | || new Set(files.map(item => item.filename)).size !== files.length |
| 136 | || files.some(item => !repositoryPath(item.filename) || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i.test(item.sha || '') |
| 137 | || (item.patch != null && (typeof item.patch !== 'string' || Buffer.byteLength(item.patch) > 8 * 1024 * 1024)))) { |
| 138 | stop('failed', 'incomplete_github_file_list'); |
| 139 | } |
| 140 | const reviews = api(`repos/${repo}/pulls/${number}/reviews?per_page=100`, true); |
| 141 | const plan = planPublication(artifact, files, reviews, reviewer); |
| 142 | snapshot(); |
| 143 | authorizeRequest(env, event, repo, number, api); |
| 144 | if (!plan) receipt = { ...receipt, outcome: 'already_published', reason: '', publication: 'deduplicated' }; |
| 145 | else { |
| 146 | const posted = api(`repos/${repo}/pulls/${number}/reviews`, false, plan); |
| 147 | if (!Number.isSafeInteger(posted.id) || posted.id <= 0 || posted.commit_id !== artifact.head_sha |
| 148 | || posted.state !== 'COMMENTED' || posted.user?.login !== reviewer) { |
| 149 | stop('publication_uncertain', 'inspect_github_before_retry'); |
| 150 | } |
| 151 | receipt = { ...receipt, outcome: 'published', reason: '', publication: 'posted', review_id: posted.id, |
| 152 | inline_comments: plan.comments.length }; |
| 153 | } |
| 154 | } catch (error) { |
| 155 | receipt = { ...receipt, outcome: error.outcome || 'failed', reason: error.reason || 'setup_failed', |
| 156 | ...(error.outcome === 'publication_uncertain' ? { publication: 'uncertain' } : {}) }; |
| 157 | } |
| 158 | writeFileSync(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 }); |
| 159 | if (env.GITHUB_OUTPUT) appendFileSync(env.GITHUB_OUTPUT, `outcome=${receipt.outcome}\nreceipt=${receiptPath}\n`); |
| 160 | if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, |
| 161 | `### Codewhale publication\n\nOutcome: **${receipt.outcome}**. ${receipt.reason ? `Reason: \`${receipt.reason}\`.` : ''}\n`); |
| 162 | const ok = ['published', 'already_published', 'superseded', 'not_eligible'].includes(receipt.outcome); |
| 163 | console.log(`${ok ? '::notice::' : '::error::'}Codewhale publication: ${receipt.outcome} (${receipt.reason || 'complete'}).`); |
| 164 | return { exitCode: ok ? 0 : 1, receipt, receiptPath }; |
| 165 | } |
| 166 | |
| 167 | if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) process.exitCode = publish().exitCode; |
| 168 |