From eb387dd86f5d45486a2c308ee35da5716b22fe40 Mon Sep 17 00:00:00 2001 From: Arthurvroum Date: Wed, 25 Nov 2026 03:41:09 +0100 Subject: [PATCH] fix: keep edits and invalid content of the ignore file Two ways of losing data in .coretrace-ignore.json: - reload() compared fingerprints only, so a reason edited on disk was replaced by the old one at the next write; - a file that could not be parsed was read as empty, so ignoring a finding overwrote it with that single entry. Every reload now takes the entries as they are on disk, and other top-level keys are kept on rewrite. A missing file ignores nothing; an unreadable or invalid one keeps the entries read before, is reported once, and add/remove refuse to touch it. Writes go through a renamed temporary file, so an interrupted write cannot truncate it. Fixes #43 --- src/ctrace/FindingIgnoreList.ts | 84 ++++++++++++++++++++++++++++----- src/extension.ts | 15 +++++- src/test/findings.test.ts | 71 +++++++++++++++++++++++++++- 3 files changed, 154 insertions(+), 16 deletions(-) diff --git a/src/ctrace/FindingIgnoreList.ts b/src/ctrace/FindingIgnoreList.ts index a2673c6..71a16a0 100644 --- a/src/ctrace/FindingIgnoreList.ts +++ b/src/ctrace/FindingIgnoreList.ts @@ -20,8 +20,12 @@ export interface IgnoredFinding { interface IgnoreFile { version: 1; ignored: IgnoredFinding[]; + [key: string]: unknown; } +/** The ignore file exists but cannot be used: it is left untouched. */ +export class IgnoreFileError extends Error {} + /** * Identifies a finding independently of its line number, so an ignored finding * stays ignored when code above it is edited. The trimmed source line is part @@ -54,12 +58,19 @@ export function relativeFindingPath(filePath: string, workspaceRoot: string | un export class FindingIgnoreList implements vscode.Disposable { private _entries = new Map(); private _serialized = ''; + // Top-level keys of the file other than "ignored", kept on rewrite. + private _extra: Record = {}; + private _problem: string | undefined; private readonly _onDidChange = new vscode.EventEmitter(); + private readonly _onDidFailToRead = new vscode.EventEmitter(); private readonly _watcher: vscode.FileSystemWatcher | undefined; /** Fires when the set of ignored fingerprints changes (from the UI or an edit of the file). */ public readonly onDidChange = this._onDidChange.event; + /** Fires with a message when the file exists but cannot be read or parsed. */ + public readonly onDidFailToRead = this._onDidFailToRead.event; + constructor(private readonly _workspaceRoot: string | undefined) { this.reload(); if (_workspaceRoot) { @@ -85,15 +96,22 @@ export class FindingIgnoreList implements vscode.Disposable { return [...this._entries.values()]; } + /** Why the file on disk cannot be used, or undefined when it can. */ + public get problem(): string | undefined { + return this._problem; + } + + /** @throws IgnoreFileError when the file exists but is unreadable or invalid. */ public async add(entry: Omit): Promise { - this.reload(); + this._reloadForWrite(); if (this._entries.has(entry.fingerprint)) { return; } this._entries.set(entry.fingerprint, { ...entry, addedAt: new Date().toISOString() }); await this._write(); } + /** @throws IgnoreFileError when the file exists but is unreadable or invalid. */ public async remove(fingerprints: string[]): Promise { - this.reload(); + this._reloadForWrite(); let changed = false; for (const fingerprint of fingerprints) { changed = this._entries.delete(fingerprint) || changed; @@ -101,30 +119,63 @@ export class FindingIgnoreList implements vscode.Disposable { if (changed) { await this._write(); } } - /** Re-reads the file. Returns true when the ignored set changed. */ + /** + * Re-reads the file. Returns true when the ignored set changed. + * + * Edits of an entry's reason or other fields are always taken, even when + * the set of fingerprints is unchanged. A missing file ignores nothing. An + * unreadable or invalid one keeps the last entries read, so that a typo + * does not bring back every ignored finding, and is reported. + */ public reload(): boolean { const file = this.filePath; let entries: IgnoredFinding[] = []; + let extra: Record = {}; + let problem: string | undefined; if (file) { try { - const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial; - entries = Array.isArray(parsed.ignored) - ? parsed.ignored.filter(e => typeof e?.fingerprint === 'string' && e.fingerprint.length > 0) - : []; - } catch { - // Missing or invalid file: nothing is ignored. + const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown; + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || !Array.isArray((parsed as IgnoreFile).ignored)) { + problem = `${IGNORE_FILE_NAME} must be an object with an "ignored" list.`; + } else { + const { ignored, ...rest } = parsed as IgnoreFile; + entries = ignored.filter(e => typeof e?.fingerprint === 'string' && e.fingerprint.length > 0); + extra = rest; + } + } catch (e) { + if ((e as NodeJS.ErrnoException).code !== 'ENOENT') { + problem = `${IGNORE_FILE_NAME} cannot be read: ${(e as Error).message}`; + } } } + + const previousProblem = this._problem; + this._problem = problem; + if (problem) { + if (problem !== previousProblem) { this._onDidFailToRead.fire(problem); } + return false; + } + + this._entries = new Map(entries.map(e => [e.fingerprint, e])); + this._extra = extra; const serialized = JSON.stringify(entries.map(e => e.fingerprint).sort()); if (serialized === this._serialized) { return false; } this._serialized = serialized; - this._entries = new Map(entries.map(e => [e.fingerprint, e])); return true; } + /** Reads the latest file before changing it, and refuses to overwrite one it cannot parse. */ + private _reloadForWrite(): void { + this.reload(); + if (this._problem) { + throw new IgnoreFileError(`${this._problem} Fix or delete the file: it was left unchanged.`); + } + } + public dispose(): void { this._watcher?.dispose(); this._onDidChange.dispose(); + this._onDidFailToRead.dispose(); } private async _write(): Promise { @@ -132,8 +183,17 @@ export class FindingIgnoreList implements vscode.Disposable { if (!file) { throw new Error('Open a workspace folder to ignore findings.'); } - const content: IgnoreFile = { version: 1, ignored: this.list() }; - await fs.promises.writeFile(file, JSON.stringify(content, null, 2) + '\n', 'utf8'); + const content: IgnoreFile = { ...this._extra, version: 1, ignored: this.list() }; + // Written next to the file then renamed over it: an interrupted write + // never leaves a truncated ignore file behind. + const staged = `${file}.${process.pid}.tmp`; + await fs.promises.writeFile(staged, JSON.stringify(content, null, 2) + '\n', 'utf8'); + try { + await fs.promises.rename(staged, file); + } catch (e) { + await fs.promises.unlink(staged).catch(() => { /* already gone */ }); + throw e; + } this._serialized = JSON.stringify(this.list().map(e => e.fingerprint).sort()); this._onDidChange.fire(); } diff --git a/src/extension.ts b/src/extension.ts index a498c0d..e6c0c00 100755 --- a/src/extension.ts +++ b/src/extension.ts @@ -109,6 +109,10 @@ export function activate(context: vscode.ExtensionContext) { sidebarProvider.postMessage({ type: 'analysis-result', data: snapshot.report, restored: true, savedAt: snapshot.savedAt, refresh: true }); } context.subscriptions.push(ignoreList.onDidChange(() => { void republishFindings(); })); + context.subscriptions.push(ignoreList.onDidFailToRead(problem => { + output.appendLine(`[ctrace] ${problem}`); + vscode.window.showWarningMessage(`${problem} The findings ignored before stay ignored until it is fixed.`); + })); // Results of unchanged files from previous workspace scans. const analysisCacheReady = initAnalysisCache(context.storageUri?.fsPath); @@ -715,7 +719,9 @@ export function activate(context: vscode.ExtensionContext) { 'Undo' ); if (action === 'Undo') { - await ignoreList.remove([finding.fingerprint]); + await ignoreList.remove([finding.fingerprint]).catch((e: Error) => { + vscode.window.showErrorMessage(`Could not restore the finding: ${e.message}`); + }); } }) ); @@ -752,7 +758,12 @@ export function activate(context: vscode.ExtensionContext) { const selected = quickPick.selectedItems.map(item => item.fingerprint); quickPick.hide(); if (selected.length > 0) { - await ignoreList.remove(selected); + try { + await ignoreList.remove(selected); + } catch (e: any) { + vscode.window.showErrorMessage(`Could not restore the findings: ${e?.message ?? e}`); + return; + } vscode.window.showInformationMessage(`${selected.length} finding${selected.length > 1 ? 's' : ''} restored.`); } }); diff --git a/src/test/findings.test.ts b/src/test/findings.test.ts index 3fda5c6..bf3ac56 100644 --- a/src/test/findings.test.ts +++ b/src/test/findings.test.ts @@ -4,7 +4,7 @@ import * as os from 'os'; import * as path from 'path'; import * as vscode from 'vscode'; import { updateDiagnostics, getFindingForDiagnostic, cweIds } from '../ctrace/DiagnosticsManager'; -import { FindingIgnoreList, computeFingerprint, IGNORE_FILE_NAME } from '../ctrace/FindingIgnoreList'; +import { FindingIgnoreList, IgnoreFileError, computeFingerprint, IGNORE_FILE_NAME } from '../ctrace/FindingIgnoreList'; import { analysisContextKey, cacheFileAnalysis, @@ -158,7 +158,74 @@ suite('Ignored findings Test Suite', () => { fs.writeFileSync(path.join(dir, IGNORE_FILE_NAME), '{ not json'); assert.doesNotThrow(() => list.reload()); - assert.deepStrictEqual(list.list(), []); + assert.ok(list.problem, 'an invalid file must be reported'); + } finally { + list.dispose(); + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + test('a reason edited on disk is kept when another finding is ignored', async () => { + const dir = tempDir('ctrace-ignore-'); + const file = path.join(dir, IGNORE_FILE_NAME); + const list = new FindingIgnoreList(dir); + try { + await list.add({ fingerprint: 'aaaa1111bbbb', ruleId: 'r1', reason: 'old reason' }); + const onDisk = JSON.parse(fs.readFileSync(file, 'utf8')); + onDisk.ignored[0].reason = 'edited by hand'; + onDisk.team = 'security'; + fs.writeFileSync(file, JSON.stringify(onDisk)); + + await list.add({ fingerprint: 'cccc2222dddd', ruleId: 'r2' }); + + const after = JSON.parse(fs.readFileSync(file, 'utf8')); + assert.strictEqual(after.ignored.find((e: any) => e.fingerprint === 'aaaa1111bbbb').reason, 'edited by hand'); + assert.ok(after.ignored.some((e: any) => e.fingerprint === 'cccc2222dddd')); + assert.strictEqual(after.team, 'security', 'other top-level keys must be kept'); + } finally { + list.dispose(); + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + test('an invalid ignore file is reported and never overwritten', async () => { + const dir = tempDir('ctrace-ignore-'); + const file = path.join(dir, IGNORE_FILE_NAME); + const list = new FindingIgnoreList(dir); + const problems: string[] = []; + list.onDidFailToRead(problem => problems.push(problem)); + try { + await list.add({ fingerprint: 'aaaa1111bbbb', ruleId: 'r1' }); + const broken = '{ "version": 1, "ignored": [ { "fingerprint": "aaaa1111bbbb", } '; + fs.writeFileSync(file, broken); + + await assert.rejects(list.add({ fingerprint: 'cccc2222dddd' }), IgnoreFileError); + await assert.rejects(list.remove(['aaaa1111bbbb']), IgnoreFileError); + assert.strictEqual(fs.readFileSync(file, 'utf8'), broken, 'the file must be left untouched'); + assert.strictEqual(problems.length, 1, 'reported once, not on every read'); + // The findings ignored before stay ignored while the file is broken. + assert.ok(list.has('aaaa1111bbbb')); + + fs.writeFileSync(file, JSON.stringify({ version: 1, ignored: [] })); + assert.strictEqual(list.reload(), true); + assert.strictEqual(list.problem, undefined); + assert.ok(!list.has('aaaa1111bbbb')); + await list.add({ fingerprint: 'cccc2222dddd' }); + assert.ok(list.has('cccc2222dddd')); + } finally { + list.dispose(); + fs.rmSync(dir, { recursive: true, force: true }); + } + }); + + test('a file that is valid JSON but not an ignore list is refused too', async () => { + const dir = tempDir('ctrace-ignore-'); + const file = path.join(dir, IGNORE_FILE_NAME); + fs.writeFileSync(file, '["not", "an", "object"]'); + const list = new FindingIgnoreList(dir); + try { + await assert.rejects(list.add({ fingerprint: 'cccc2222dddd' }), IgnoreFileError); + assert.strictEqual(fs.readFileSync(file, 'utf8'), '["not", "an", "object"]'); } finally { list.dispose(); fs.rmSync(dir, { recursive: true, force: true });