diff --git a/bin/semgrep-retry.mjs b/bin/semgrep-retry.mjs index dfe06ba3..aca49c14 100644 --- a/bin/semgrep-retry.mjs +++ b/bin/semgrep-retry.mjs @@ -9,6 +9,13 @@ // main scan's JSON, this step first copies those entries into the SARIF as an invocation carrying // properties.commitworkFixpoint, so the reader counts them as files read in part too. // +// The JSON errors[] array is a second such record, and it is NOT the same set as the notices: on a +// 436k-line C tree 249 files were named by errors[] and 252 by the notices, and machdep.h ("Other +// syntax error") appeared in the JSON alone. A file the notices omit is a file the reader counts as +// clean, so the files errors[] names and the notices do not are copied in the same way, under +// properties.commitworkJsonErrors. Only the types that mean "read only in part" are copied; a type +// this script does not know is counted in the receipt rather than guessed at. +// // It then scans the files whose reasons include `timeout` or `fixpoint-timeout`, and only those, // again with a long per-rule timeout and no skip threshold, and merges what it finds into the lane // SARIF. A retry of a fixpoint-timeout file runs at one job: measured on 15 live-composer files, @@ -77,6 +84,18 @@ export function retryControls(env = process.env) { const FIXPOINT_AT = /^Fixpoint timeout while performing taint analysis at (.+?):(\d+):(\d+)/; +// The errors[] types that mean "this file was read only in part", mapped to the reason the SARIF +// reader already uses for the same notice. `PartialParsing` is a parse that failed on some +// constructs, which the notices report as a syntax error; measured on the Hercules tree, 26 +// "Syntax error" + 196 "PartialParsing" entries lined up with 222 syntax-error files. +const JSON_ERROR_REASONS = Object.freeze({ + 'Syntax error': 'syntax-error', + 'Other syntax error': 'syntax-error', + 'Lexical error': 'lexical-error', + 'Timeout': 'timeout', + 'PartialParsing': 'syntax-error', +}); + /** Semgrep's JSON time.fixpoint_timeouts, placed: {measured, json, count, unattributed, entries} * sorted by uri then line, or {measured:false, json, reason}. Only ENOENT reads as not written. */ export function readFixpoint(path) { @@ -105,10 +124,54 @@ export function readFixpoint(path) { return { measured: true, json, count: list.length, unattributed: list.length - entries.length, entries }; } +/** Semgrep's JSON errors[] as {uri, reason, message}, deduped per file+reason and sorted, or + * {measured:false, json, reason}. `unclassified` counts entries whose type this script does not + * map or that name no file, so a type Semgrep adds later is visible rather than silently dropped. + * Only ENOENT reads as not written. */ +export function readJsonErrors(path) { + const json = basename(path); + const blind = (reason) => ({ measured: false, json, reason }); + let text; + try { text = readFileSync(path, 'utf8'); } catch (e) { + return blind(e.code === 'ENOENT' ? `${json} was not written` : `${json} could not be read — ${e.code || e.message}`); + } + let doc; + try { doc = JSON.parse(text); } catch (e) { return blind(`${json} is not valid JSON — ${e.message}`); } + const list = doc && doc.errors; + if (!Array.isArray(list)) return blind(`${json} carries no errors[]`); + const seen = new Set(); + const entries = []; + let unclassified = 0; + for (const e of list) { + // Semgrep writes `type` as a string for a syntax error and as an ARRAY for a partial parse + // (["PartialParsing", {...}]), so String(type) would never match the map for the latter. + const type = typeof (e && e.type) === 'string' ? e.type + : Array.isArray(e && e.type) && typeof e.type[0] === 'string' ? e.type[0] : ''; + const reason = JSON_ERROR_REASONS[type]; + const uri = (e && typeof e.path === 'string' && e.path) + || (e && e.spans && e.spans[0] && e.spans[0].file) || null; + if (!reason || !uri) { unclassified++; continue; } + const key = `${uri}\u0000${reason}`; + if (seen.has(key)) continue; + seen.add(key); + const message = typeof (e && e.message) === 'string' && e.message ? e.message : `${type} at ${uri}`; + entries.push({ uri, reason, message }); + } + entries.sort((a, b) => (a.uri < b.uri ? -1 : a.uri > b.uri ? 1 : a.reason < b.reason ? -1 : a.reason > b.reason ? 1 : 0)); + return { measured: true, json, count: list.length, unclassified, entries }; +} + const fixpointNotice = (e) => ({ descriptor: { id: 'Fixpoint timeout' }, level: 'warning', message: { text: e.message }, locations: [{ physicalLocation: { artifactLocation: { uri: e.uri }, region: { startLine: e.line, ...(e.col ? { startColumn: e.col } : {}) } } }], }); +// The descriptor id is what monitor/sarif-read.mjs keys its reason map on, so it must be the id the +// notices use for that reason rather than the reason word itself. +const NOTICE_ID_OF = Object.freeze({ 'timeout': 'Timeout', 'lexical-error': 'Lexical error', 'syntax-error': 'Syntax error' }); +const jsonErrorNotice = (e) => ({ + descriptor: { id: NOTICE_ID_OF[e.reason] || 'Syntax error' }, level: 'warning', message: { text: e.message }, + locations: [{ physicalLocation: { artifactLocation: { uri: e.uri } } }], +}); const withoutEntries = ({ entries, ...rest }) => rest; const stem = (sarifPath) => `${basename(sarifPath).replace(/\.sarif$/, '')}-retry`; @@ -210,8 +273,9 @@ export function retrySemgrep({ sarifPath, jsonPath = null, bin = 'semgrep', conf const at = nowISO(env); const base = { tool: 'semgrep-retry', sarif: basename(sarif), bin, timeoutSec: ctl.timeoutSec, timeoutThreshold: 0, maxFiles: ctl.maxFiles, batchFiles: ctl.batchFiles, budgetSec: ctl.budgetSec, at }; const fixpoint = detectFixpoint(sarif, jsonPath); + const jsonErrors = detectJsonErrors(sarif, jsonPath); const done = (state, extra = {}) => { - const receipt = { ...base, state, fixpoint, ...extra }; + const receipt = { ...base, state, fixpoint, jsonErrors, ...extra }; writeAtomic(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`); return receipt; }; @@ -320,6 +384,41 @@ function detectFixpoint(sarif, jsonPath) { return { ...out, injected: fx.entries.length }; } +/** Copy the files Semgrep's JSON errors[] names and its SARIF notices do not into the SARIF once, as + * their own invocation, so a file the notices omitted is still counted as read only in part. A file + * the notices already name is left alone: injecting it again would inflate the notice count without + * changing the file count. Returns the receipt's `jsonErrors` field. */ +function detectJsonErrors(sarif, jsonPath) { + if (!jsonPath) return { measured: false, reason: 'no Semgrep JSON was given (--json)' }; + const je = readJsonErrors(resolve(jsonPath)); + if (!je.measured) return je; + const out = { ...withoutEntries(je), injected: 0 }; + if (!je.entries.length) return out; + const read = readSarif(sarif); + if (read.state !== 'ok') return { ...out, reason: `the SARIF reads ${read.state}, so the errors[] files were not recorded in it` }; + if ((read.runs[0].invocations || []).some((i) => i && i.properties && i.properties.commitworkJsonErrors)) return out; + // A file the retry already resolved is one the notices DID name: partialLedger cleared its row + // because the retry re-measured it, not because the notices omitted it. Injecting it back would add + // a fact the ledger clears again, and the receipt would claim a recovery that is not one. + const named = new Set([ + ...(read.partialAnalysis || []).map((p) => p.uri), + ...((read.partialRetry && read.partialRetry.recovered) || []), + ]); + const missing = je.entries.filter((e) => !named.has(e.uri)); + if (!missing.length) return out; + let doc; + try { doc = JSON.parse(readFileSync(sarif, 'utf8')); } catch (e) { return { ...out, reason: `the SARIF could not be re-read for the record — ${e.message}` }; } + const run = doc.runs[0]; + if (!Array.isArray(run.invocations)) run.invocations = []; + run.invocations.push({ + executionSuccessful: true, + toolExecutionNotifications: missing.map(jsonErrorNotice), + properties: { commitworkJsonErrors: { source: 'errors[]', json: je.json, count: je.count, injected: missing.length } }, + }); + writeAtomic(sarif, JSON.stringify(doc)); + return { ...out, injected: missing.length }; +} + if (isMainModule(import.meta.url)) { const argv = process.argv.slice(2); const dash = argv.indexOf('--'); @@ -341,6 +440,10 @@ if (isMainModule(import.meta.url)) { const fixpoint = fx.measured ? `; ${fx.count} fixpoint timeout(s) recorded from ${fx.json}${fx.unattributed ? `, ${fx.unattributed} not attributable to a file` : ''}${fx.reason ? ` — ${fx.reason}` : ''}` : `; fixpoint timeouts not measured — ${fx.reason}`; - process.stderr.write(`semgrep-retry: ${summary}${fixpoint}\n`); + const je = receipt.jsonErrors; + const jsonErrors = je && je.measured + ? `; ${je.injected} file(s) named by errors[] but not by the notices recorded from ${je.json}${je.unclassified ? `, ${je.unclassified} error(s) of an unmapped type` : ''}${je.reason ? ` — ${je.reason}` : ''}` + : `; errors[] not measured — ${je ? je.reason : 'no Semgrep JSON was given (--json)'}`; + process.stderr.write(`semgrep-retry: ${summary}${fixpoint}${jsonErrors}\n`); } } diff --git a/bin/test/semgrep-retry.test.mjs b/bin/test/semgrep-retry.test.mjs index 9280afc0..d399f1e4 100644 --- a/bin/test/semgrep-retry.test.mjs +++ b/bin/test/semgrep-retry.test.mjs @@ -11,7 +11,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, chmodSync, existsS import { tmpdir } from 'node:os'; import { join, dirname } from 'node:path'; import { fileURLToPath } from 'node:url'; -import { retrySemgrep, mergeRetry, resultKey, retryControls, readFixpoint, DEFAULTS } from '../semgrep-retry.mjs'; +import { retrySemgrep, mergeRetry, resultKey, retryControls, readFixpoint, readJsonErrors, DEFAULTS } from '../semgrep-retry.mjs'; import { readSarif, describePartial, RETRIED_REASONS } from '../../monitor/sarif-read.mjs'; import { parseSarif } from '../lib/report-parsers/sarif.mjs'; import { _sarifCounts } from '../../monitor/extractors.mjs'; @@ -695,7 +695,7 @@ describe('the command line', { skip: process.platform === 'win32' && 'the stub i cwd: fx.scan, encoding: 'utf8', env: { ...ENV, PATH: `${bin}:${process.env.PATH}` }, }); assert.equal(r.status, 0, r.stderr); - assert.match(r.stderr, /retried 2 file\(s\) at 60s per rule: 2 recovered, 0 still timing out, 1 result\(s\) added, 1 not retried; 1 fixpoint timeout\(s\) recorded from semgrep\.json\n$/); + assert.match(r.stderr, /retried 2 file\(s\) at 60s per rule: 2 recovered, 0 still timing out, 1 result\(s\) added, 1 not retried; 1 fixpoint timeout\(s\) recorded from semgrep\.json; 0 file\(s\) named by errors\[\] but not by the notices recorded from semgrep\.json\n$/); const argv = readFileSync(join(fx.dir, 'argv'), 'utf8').trim().split('\n'); assert.equal(argv[argv.indexOf('-j') + 1], '1'); assert.deepEqual(uris(readSarif(fx.sarif).partialAnalysis), ['c.js']); @@ -707,3 +707,97 @@ describe('the command line', { skip: process.platform === 'win32' && 'the stub i assert.match(r.stderr, /usage/); }); }); + +// Semgrep's JSON errors[] and its SARIF notices are two records of the same run, and they are not the +// same set: on a 436k-line C tree the notices named 252 files and errors[] named 249, with one file +// (machdep.h, "Other syntax error") in the JSON alone. The notices are the only thing the reader sees, +// so a file the notices omit is a file the lane reports clean. These cases pin the cross-check that +// copies the omitted files in, and the two ways it must NOT fire: a file the notices already name, and +// a file the retry already re-measured. +describe('the JSON errors[] cross-check', () => { + const errorsJson = (errors) => ({ version: '1.180.0', results: [], errors, time: { fixpoint_timeouts: [] } }); + const retriedDoc = (notifications, retry) => ({ + version: '2.1.0', + runs: [{ + tool: { driver: { name: 'Semgrep OSS', semanticVersion: '1.180.0', rules: [{ id: PLANTED }] } }, + results: [], + invocations: [ + { executionSuccessful: true, toolExecutionNotifications: notifications }, + { executionSuccessful: true, toolExecutionNotifications: [], properties: { commitworkRetry: retry } }, + ], + }], + }); + + test('readJsonErrors maps a string type and an array type, dedupes per file+reason, and counts what it cannot map', () => { + const dir = mkdtempSync(join(tmpdir(), 'cw-sg-jsonerr-')); + const p = join(dir, 'semgrep.json'); + writeFileSync(p, JSON.stringify(errorsJson([ + { type: 'Other syntax error', path: 'a.c', message: 'Other syntax error at line a.c:1:' }, + { type: 'Syntax error', path: 'a.c', message: 'Syntax error at line a.c:2:' }, + { type: ['PartialParsing', { x: 1 }], path: 'b.c', message: 'PartialParsing' }, + { type: 'Timeout', path: 'c.c', message: 'Timeout when running r on c.c:' }, + { type: 'SomethingNew', path: 'd.c', message: 'a type this script does not know' }, + { type: 'Timeout', path: null, message: 'names no file' }, + ]))); + const r = readJsonErrors(p); + assert.equal(r.measured, true); + assert.equal(r.count, 6); + assert.equal(r.unclassified, 2, 'an unmapped type and an entry naming no file are counted, never guessed at'); + assert.deepEqual(r.entries.map((e) => `${e.uri}:${e.reason}`), ['a.c:syntax-error', 'b.c:syntax-error', 'c.c:timeout'], + 'the array-typed PartialParsing maps like the string-typed syntax error, and a.c is one row'); + }); + + test('a file errors[] names and the notices do not is injected, and only that file', () => { + const fx = fixture([syntax('a.js')]); + const jsonPath = join(fx.out, 'semgrep.json'); + writeFileSync(jsonPath, JSON.stringify(errorsJson([ + { type: 'Syntax error', path: 'a.js', message: 'Syntax error at line a.js:3:' }, + { type: 'Other syntax error', path: 'b.js', message: 'Other syntax error at line b.js:1:' }, + ]))); + const r = retrySemgrep({ sarifPath: fx.sarif, jsonPath, env: { ...ENV, CW_SEMGREP_RETRY: '0' } }); + assert.equal(r.state, 'disabled'); + assert.equal(r.jsonErrors.injected, 1, 'a.js is already named; only b.js is missing'); + assert.deepEqual(uris(readSarif(fx.sarif).partialAnalysis), ['a.js', 'b.js']); + }); + + test('a file the notices already name is not injected again', () => { + const fx = fixture([syntax('a.js')]); + const jsonPath = join(fx.out, 'semgrep.json'); + writeFileSync(jsonPath, JSON.stringify(errorsJson([{ type: 'Syntax error', path: 'a.js', message: 'x' }]))); + const r = retrySemgrep({ sarifPath: fx.sarif, jsonPath, env: { ...ENV, CW_SEMGREP_RETRY: '0' } }); + assert.equal(r.jsonErrors.injected, 0); + assert.deepEqual(uris(readSarif(fx.sarif).partialAnalysis), ['a.js'], 'the notice count is not inflated'); + }); + + test('a file the retry already resolved is not injected back', () => { + const dir = mkdtempSync(join(tmpdir(), 'cw-sg-jsonerr-')); + const sarif = join(dir, 'semgrep.sarif'); + writeFileSync(sarif, JSON.stringify(retriedDoc([timeout(RULE, 'a.js')], { files: ['a.js'], timeoutSec: 60, fixpointMeasured: true }))); + const jsonPath = join(dir, 'semgrep.json'); + writeFileSync(jsonPath, JSON.stringify(errorsJson([{ type: 'Timeout', path: 'a.js', message: 'Timeout when running r on a.js:' }]))); + const r = retrySemgrep({ sarifPath: sarif, jsonPath, env: { ...ENV, CW_SEMGREP_RETRY: '0' } }); + assert.equal(r.jsonErrors.injected, 0, + 'the retry re-measured it, so the notices DID name it; injecting it back would claim a recovery that is not one'); + assert.deepEqual(uris(readSarif(sarif).partialAnalysis), []); + }); + + test('a second pass injects nothing', () => { + const fx = fixture([syntax('a.js')]); + const jsonPath = join(fx.out, 'semgrep.json'); + writeFileSync(jsonPath, JSON.stringify(errorsJson([{ type: 'Other syntax error', path: 'b.js', message: 'x' }]))); + const first = retrySemgrep({ sarifPath: fx.sarif, jsonPath, env: { ...ENV, CW_SEMGREP_RETRY: '0' } }); + assert.equal(first.jsonErrors.injected, 1); + const second = retrySemgrep({ sarifPath: fx.sarif, jsonPath, env: { ...ENV, CW_SEMGREP_RETRY: '0' } }); + assert.equal(second.jsonErrors.injected, 0, 'the invocation is the record; a second pass must not stack one'); + assert.deepEqual(uris(readSarif(fx.sarif).partialAnalysis), ['a.js', 'b.js']); + }); + + test('no --json leaves the SARIF untouched and says so', () => { + const fx = fixture([syntax('a.js')]); + const before = readFileSync(fx.sarif, 'utf8'); + const r = retrySemgrep({ sarifPath: fx.sarif, env: { ...ENV, CW_SEMGREP_RETRY: '0' } }); + assert.equal(r.jsonErrors.measured, false); + assert.match(r.jsonErrors.reason, /no Semgrep JSON was given/); + assert.equal(readFileSync(fx.sarif, 'utf8'), before, 'byte-identical when there is nothing to read'); + }); +}); diff --git a/package.json b/package.json index 7cccc60d..201b2ab2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "commitwork", - "version": "0.6.347", + "version": "0.6.348", "description": "Repository security scanner, local CI runner and scheduled monitor, with remediation and compliance-evidence tooling. Manifest-driven; runs against any git repository.", "homepage": "https://www.commitwork.online", "repository": {