Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 72 additions & 12 deletions src/ctrace/FindingIgnoreList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -54,12 +58,19 @@ export function relativeFindingPath(filePath: string, workspaceRoot: string | un
export class FindingIgnoreList implements vscode.Disposable {
private _entries = new Map<string, IgnoredFinding>();
private _serialized = '';
// Top-level keys of the file other than "ignored", kept on rewrite.
private _extra: Record<string, unknown> = {};
private _problem: string | undefined;
private readonly _onDidChange = new vscode.EventEmitter<void>();
private readonly _onDidFailToRead = new vscode.EventEmitter<string>();
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) {
Expand All @@ -85,55 +96,104 @@ 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<IgnoredFinding, 'addedAt'>): Promise<void> {
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<void> {
this.reload();
this._reloadForWrite();
let changed = false;
for (const fingerprint of fingerprints) {
changed = this._entries.delete(fingerprint) || changed;
}
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<string, unknown> = {};
let problem: string | undefined;
if (file) {
try {
const parsed = JSON.parse(fs.readFileSync(file, 'utf8')) as Partial<IgnoreFile>;
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<void> {
const file = this.filePath;
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();
}
Expand Down
15 changes: 13 additions & 2 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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}`);
});
}
})
);
Expand Down Expand Up @@ -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.`);
}
});
Expand Down
71 changes: 69 additions & 2 deletions src/test/findings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 });
Expand Down
Loading