| 1 | import { createHash } from 'node:crypto'; |
| 2 | import { KEYS } from './setup.mjs'; |
| 3 | |
| 4 | const SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/i; |
| 5 | const REPO = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; |
| 6 | const MAX_BYTES = 2 * 1024 * 1024; |
| 7 | |
| 8 | function requireValue(valid) { |
| 9 | if (!valid) throw new Error('invalid_findings_artifact'); |
| 10 | } |
| 11 | |
| 12 | function text(value, max = 20000) { |
| 13 | requireValue(typeof value === 'string' && value.length <= max && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value)); |
| 14 | return value; |
| 15 | } |
| 16 | |
| 17 | export function repositoryPath(value) { |
| 18 | return typeof value === 'string' && value.length > 0 && value.length <= 4096 |
| 19 | && !/[\\\u0000-\u001f\u007f]/.test(value) && !value.startsWith('/') |
| 20 | && !value.split('/').some(part => !part || part === '.' || part === '..'); |
| 21 | } |
| 22 | |
| 23 | function location(value) { |
| 24 | requireValue(value.path == null || repositoryPath(value.path)); |
| 25 | requireValue(value.line == null || (Number.isSafeInteger(value.line) && value.line > 0)); |
| 26 | return { path: value.path ?? null, line: value.line ?? null }; |
| 27 | } |
| 28 | |
| 29 | function list(value, convert, max = 200) { |
| 30 | requireValue(Array.isArray(value) && value.length <= max); |
| 31 | return value.map(convert); |
| 32 | } |
| 33 | |
| 34 | function review(value) { |
| 35 | requireValue(value && typeof value === 'object'); |
| 36 | const result = { |
| 37 | summary: text(value.summary), |
| 38 | issues: list(value.issues, issue => { |
| 39 | requireValue(issue && ['blocker', 'concern', 'nit', 'error', 'warning', 'info', 'high', 'medium', 'low', 'critical'].includes(issue.severity)); |
| 40 | requireValue(issue.authorship == null || ['introduced', 'preexisting'].includes(issue.authorship)); |
| 41 | requireValue(issue.inline_anchorable == null || typeof issue.inline_anchorable === 'boolean'); |
| 42 | const item = { ...location(issue), severity: issue.severity, title: text(issue.title, 1000), |
| 43 | description: text(issue.description), authorship: issue.authorship ?? null, |
| 44 | inline_anchorable: issue.inline_anchorable ?? null }; |
| 45 | if (issue.evidence != null) { |
| 46 | requireValue(['reproduced', 'traced', 'suspected'].includes(issue.evidence.tier)); |
| 47 | item.evidence = { tier: issue.evidence.tier, detail: text(issue.evidence.detail) }; |
| 48 | } |
| 49 | if (issue.contract != null) item.contract = { became: text(issue.contract.became), |
| 50 | dependents_checked: list(issue.contract.dependents_checked, item => text(item, 4096), 100) }; |
| 51 | if (issue.kind != null) { |
| 52 | requireValue(['defect', 'intent', 'contract'].includes(issue.kind)); |
| 53 | item.kind = issue.kind; |
| 54 | } |
| 55 | return item; |
| 56 | }), |
| 57 | suggestions: list(value.suggestions, item => ({ ...location(item), suggestion: text(item.suggestion) })), |
| 58 | overall_assessment: text(value.overall_assessment), |
| 59 | verified: list(value.verified ?? [], item => text(item), 100), |
| 60 | not_reviewed: list(value.not_reviewed ?? [], item => text(item), 100), |
| 61 | ruled_out: list(value.ruled_out ?? [], item => text(item), 100), |
| 62 | }; |
| 63 | if (value.merge_risk != null) { |
| 64 | requireValue(['low', 'medium', 'high'].includes(value.merge_risk.level)); |
| 65 | result.merge_risk = { level: value.merge_risk.level, reason: text(value.merge_risk.reason) }; |
| 66 | } |
| 67 | return result; |
| 68 | } |
| 69 | |
| 70 | export function validateArtifact(value) { |
| 71 | requireValue(value?.schema_version === 1 && value.kind === 'codewhale-review-findings'); |
| 72 | requireValue(REPO.test(value.repository || '') && Number.isSafeInteger(value.pr_number) && value.pr_number > 0); |
| 73 | requireValue(SHA.test(value.base_sha || '') && SHA.test(value.head_sha || '')); |
| 74 | requireValue(/^[1-9][0-9]*$/.test(value.run_id || '') && /^[1-9][0-9]*$/.test(value.run_attempt || '')); |
| 75 | requireValue(value.complete === true && value.publication === 'not_requested'); |
| 76 | requireValue(Number.isSafeInteger(value.review_passes) && value.review_passes > 0 && value.review_passes <= 64); |
| 77 | const result = { schema_version: 1, kind: value.kind, repository: value.repository, pr_number: value.pr_number, |
| 78 | base_sha: value.base_sha, head_sha: value.head_sha, run_id: value.run_id, run_attempt: value.run_attempt, |
| 79 | complete: true, publication: 'not_requested', review_passes: value.review_passes, review: review(value.review) }; |
| 80 | requireValue(Buffer.byteLength(JSON.stringify(result)) <= MAX_BYTES); |
| 81 | return result; |
| 82 | } |
| 83 | |
| 84 | export function parseArtifact(raw) { |
| 85 | requireValue(Buffer.byteLength(raw) <= MAX_BYTES); |
| 86 | return validateArtifact(JSON.parse(raw)); |
| 87 | } |
| 88 | |
| 89 | export function findingsArtifact(data, receipt, env) { |
| 90 | const secrets = ['GH_TOKEN', ...Object.values(KEYS)].map(key => env[key]).filter(Boolean); |
| 91 | const clean = value => typeof value === 'string' |
| 92 | ? secrets.reduce((result, secret) => result.split(secret).join('[REDACTED]'), value) |
| 93 | : Array.isArray(value) ? value.map(clean) |
| 94 | : value && typeof value === 'object' ? Object.fromEntries(Object.entries(value).map(([key, item]) => [key, clean(item)])) : value; |
| 95 | return validateArtifact({ schema_version: 1, kind: 'codewhale-review-findings', repository: receipt.repository, |
| 96 | pr_number: receipt.pr_number, base_sha: receipt.base_sha, head_sha: receipt.head_sha, |
| 97 | run_id: env.GITHUB_RUN_ID, run_attempt: env.GITHUB_RUN_ATTEMPT, complete: true, |
| 98 | publication: 'not_requested', review_passes: data.review_passes, review: clean(review(data.review)) }); |
| 99 | } |
| 100 | |
| 101 | export function fingerprint(value) { |
| 102 | return createHash('sha256').update(JSON.stringify(value)).digest('hex'); |
| 103 | } |
| 104 | |
| 105 | export function markdown(value) { |
| 106 | return value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>') |
| 107 | .replaceAll('@', '@').replace(/[\\`*_{}\[\]()!|#~]/g, '\\$&'); |
| 108 | } |
| 109 | |
| 110 | export function issueBody(issue) { |
| 111 | let body = `**[${issue.severity.toUpperCase()}] ${markdown(issue.title)}**\n\n${markdown(issue.description)}`; |
| 112 | if (issue.evidence) body += `\n\n${issue.evidence.tier}: ${markdown(issue.evidence.detail)}`; |
| 113 | if (issue.contract) body += `\n\nContract: ${markdown(issue.contract.became)}\n\nDependents checked: ${issue.contract.dependents_checked.map(markdown).join(', ')}`; |
| 114 | return body; |
| 115 | } |
| 116 | |
| 117 | export function hasRecordedEvidence(issue) { |
| 118 | return ['reproduced', 'traced'].includes(issue.evidence?.tier) |
| 119 | && typeof issue.evidence.detail === 'string' && issue.evidence.detail.trim().length > 0; |
| 120 | } |
| 121 | |
| 122 | export function renderSummary(value, issues, duplicateCount, withheldCount = 0) { |
| 123 | const result = ['## Codewhale review', `Reviewed commit: ${value.head_sha}`, |
| 124 | issues.length ? `${issues.length} finding(s) with recorded evidence.` |
| 125 | : 'No new findings met the publication evidence requirement.']; |
| 126 | for (const issue of issues.filter(item => item.authorship !== 'preexisting')) { |
| 127 | const location = issue.path ? `\n\nLocation: ${markdown(issue.path)}${issue.line ? `:${issue.line}` : ''}` : ''; |
| 128 | result.push(`${issue.authorship == null ? 'Attribution to this change was not recorded.\n\n' : ''}${issueBody(issue)}${location}`); |
| 129 | } |
| 130 | const preexisting = issues.filter(item => item.authorship === 'preexisting'); |
| 131 | if (preexisting.length) result.push('<details><summary>Pre-existing findings</summary>\n\n' |
| 132 | + preexisting.map(issue => `${issueBody(issue)}${issue.path ? `\n\nLocation: ${markdown(issue.path)}${issue.line ? `:${issue.line}` : ''}` : ''}`).join('\n\n') |
| 133 | + '\n\n</details>'); |
| 134 | if (duplicateCount) result.push(`${duplicateCount} finding(s) already reported by this publisher on unchanged file content were omitted.`); |
| 135 | if (withheldCount) result.push(`${withheldCount} candidate finding(s) had missing, empty or suspected evidence and were withheld. Investigation details remain in the analysis artifact.`); |
| 136 | result.push(`[Analysis and coverage](https://github.com/${value.repository}/actions/runs/${value.run_id}). Recorded evidence is supplied by the reviewer; publication does not independently reproduce it.`, |
| 137 | 'Advisory review, not an approval or proof that the change is bug-free. Binary contents and arbitrary unchanged callers are outside its coverage.'); |
| 138 | return result.filter(Boolean).join('\n\n'); |
| 139 | } |
| 140 |