Merge pull request #3515 from rudycelekli/fix/security-scan-machine-output-3511

fix(security): produce valid JSON and SARIF scan output
This commit is contained in:
rUv authored and GitHub committed 2026-09-28 11:24:57 -04:00
commit 635bbff020
2 files changed
+205 -54

No files matched your search

@@ -0,0 +1,96 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import type { CommandContext } from '../src/types.js';
const captured = vi.hoisted(() => ({ stdout: [] as string[], stderr: [] as string[] }));
vi.mock('../src/output.js', () => ({
output: {
writeln: (value = '') => { captured.stdout.push(value); },
printJson: (value: unknown) => { captured.stdout.push(JSON.stringify(value)); },
printTable: () => { captured.stdout.push('<table>'); },
printBox: () => { captured.stdout.push('<box>'); },
printError: (value: string) => { captured.stderr.push(value); },
printWarning: (value: string) => { captured.stderr.push(value); },
bold: (value: string) => value,
dim: (value: string) => value,
success: (value: string) => value,
error: (value: string) => value,
warning: (value: string) => value,
info: (value: string) => value,
createSpinner: () => ({
start: () => { captured.stdout.push('<spinner-start>'); },
setText: () => {},
succeed: () => { captured.stdout.push('<spinner-success>'); },
fail: () => { captured.stdout.push('<spinner-fail>'); },
}),
},
}));
import { securityCommand } from '../src/commands/security.js';
const scan = securityCommand.subcommands!.find(command => command.name === 'scan')!;
let target: string;
async function run(outputFormat: string) {
const ctx: CommandContext = {
args: [],
flags: { _: [], target, depth: 'quick', type: 'code', output: outputFormat },
cwd: target,
interactive: false,
};
return scan.action!(ctx);
}
beforeEach(() => {
captured.stdout.length = 0;
captured.stderr.length = 0;
target = mkdtempSync(join(tmpdir(), 'ruflo-scan-output-'));
writeFileSync(join(target, 'secret.ts'), 'export const key = "AKIAIOSFODNN7EXAMPLE";\n');
});
afterEach(() => {
rmSync(target, { recursive: true, force: true });
});
describe('security scan machine-readable output', () => {
it('retains the human-readable scan summary for text output', async () => {
const result = await run('text');
expect(result.success).toBe(false);
expect(captured.stdout).toContain('Security Scan');
expect(captured.stdout).toContain('<table>');
expect(captured.stdout).toContain('<box>');
});
it('prints one valid JSON document with raw severity and no text progress', async () => {
const result = await run('json');
expect(result.success).toBe(false); // A high-severity finding keeps the scan gate.
expect(captured.stdout).toHaveLength(1);
const record = JSON.parse(captured.stdout[0]);
expect(record.summary).toMatchObject({ high: 1, total: 1 });
expect(record.findings[0]).toMatchObject({ severity: 'high', type: 'Hardcoded Secret', location: 'secret.ts:1' });
const persisted = JSON.parse(readFileSync(join(target, '.claude/security-scans/scan-code-quick.json'), 'utf8'));
expect(persisted.findings).toEqual(record.findings);
});
it('prints a SARIF 2.1.0 document with a rule, result, and source location', async () => {
const result = await run('sarif');
expect(result.success).toBe(false);
expect(captured.stdout).toHaveLength(1);
const sarif = JSON.parse(captured.stdout[0]);
expect(sarif.version).toBe('2.1.0');
expect(sarif.runs[0].tool.driver.rules).toHaveLength(1);
expect(sarif.runs[0].results[0]).toMatchObject({
level: 'error',
locations: [{ physicalLocation: { artifactLocation: { uri: 'secret.ts' }, region: { startLine: 1 } } }],
});
});
it('rejects an unknown format before scanning or reporting clean', async () => {
const result = await run('xml');
expect(result).toMatchObject({ success: false, exitCode: 1 });
expect(captured.stdout).toEqual([]);
expect(captured.stderr.join('\n')).toContain('Invalid --output');
});
});
+109 -54
View File
@@ -16,8 +16,12 @@ import { createBuiltinAIDefence, type DefenceEngine } from '../security/builtin-
// for both validation and the traversal-depth maps below.
const SCAN_DEPTHS = ['quick', 'standard', 'deep'] as const;
const SCAN_TYPES = ['code', 'deps', 'all'] as const;
const SCAN_OUTPUTS = ['text', 'json', 'sarif'] as const;
type ScanDepth = (typeof SCAN_DEPTHS)[number];
type ScanType = (typeof SCAN_TYPES)[number];
type ScanOutput = (typeof SCAN_OUTPUTS)[number];
type ScanSeverity = 'critical' | 'high' | 'medium' | 'low';
type ScanFinding = { severity: ScanSeverity; type: string; location: string; description: string };
// Real type predicates, not `as` casts. Array.includes() does not narrow a
// string to a literal union on its own, so without these the depth-map lookups
@@ -29,6 +33,38 @@ type ScanType = (typeof SCAN_TYPES)[number];
// is being fixed for.
const isScanDepth = (v: string): v is ScanDepth => (SCAN_DEPTHS as readonly string[]).includes(v);
const isScanType = (v: string): v is ScanType => (SCAN_TYPES as readonly string[]).includes(v);
const isScanOutput = (v: string): v is ScanOutput => (SCAN_OUTPUTS as readonly string[]).includes(v);
function scanSarif(findings: ScanFinding[]) {
const ruleId = (type: string) => `RUFLO-${type.toUpperCase().replace(/[^A-Z0-9]+/g, '-')}`;
const level = (severity: ScanSeverity) => severity === 'critical' || severity === 'high' ? 'error' :
severity === 'medium' ? 'warning' : 'note';
const rules = [...new Map(findings.map(finding => [finding.type, {
id: ruleId(finding.type),
name: finding.type,
shortDescription: { text: finding.type },
}])).values()];
return {
version: '2.1.0',
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
runs: [{
tool: { driver: { name: 'Ruflo Security Scan', rules } },
results: findings.map(finding => {
const lineMatch = /^(.*):(\d+)$/.exec(finding.location);
const file = lineMatch?.[1] ?? (finding.location.startsWith('package.json:') ? 'package.json' : finding.location);
return {
ruleId: ruleId(finding.type),
level: level(finding.severity),
message: { text: finding.description },
locations: [{ physicalLocation: {
artifactLocation: { uri: file.replace(/\\/g, '/') },
...(lineMatch ? { region: { startLine: Number(lineMatch[2]) } } : {}),
} }],
};
}),
}],
};
}
// `full` was never a supported depth, but the CLI itself printed it — the
// statusline insight, the announcement, the release-notes blurb, the CLAUDE.md
@@ -72,6 +108,7 @@ const scanCommand: Command = {
const target = ctx.flags.target as string || '.';
const requestedDepth = ctx.flags.depth as string || 'standard';
const scanType = ctx.flags.type as string || 'all';
const requestedOutput = ctx.flags.output as string || 'text';
const fix = ctx.flags.fix as boolean;
// A security scanner must never silently degrade on an unrecognised enum
@@ -111,6 +148,11 @@ const scanCommand: Command = {
);
return { success: false, exitCode: 1 };
}
if (!isScanOutput(requestedOutput)) {
output.printError(`Invalid --output '${requestedOutput}'. Expected one of: ${SCAN_OUTPUTS.join(', ')}.`);
return { success: false, exitCode: 1 };
}
const outputFormat: ScanOutput = requestedOutput;
// --target names WHAT gets scanned, and was never validated. A path that
// does not exist (or is a file, not a directory) made every phase read
@@ -128,14 +170,16 @@ const scanCommand: Command = {
return { success: false, exitCode: 1 };
}
output.writeln();
output.writeln(output.bold('Security Scan'));
output.writeln(output.dim('─'.repeat(50)));
if (outputFormat === 'text') {
output.writeln();
output.writeln(output.bold('Security Scan'));
output.writeln(output.dim('─'.repeat(50)));
}
const spinner = output.createSpinner({ text: `Scanning ${target}...`, spinner: 'dots' });
spinner.start();
if (outputFormat === 'text') spinner.start();
const findings: Array<{ severity: string; type: string; location: string; description: string }> = [];
const findings: ScanFinding[] = [];
let criticalCount = 0, highCount = 0, mediumCount = 0, lowCount = 0;
try {
@@ -174,9 +218,9 @@ const scanCommand: Command = {
else lowCount++;
findings.push({
severity: sev === 'critical' ? output.error('CRITICAL') :
sev === 'high' ? output.warning('HIGH') :
sev === 'moderate' || sev === 'medium' ? output.warning('MEDIUM') : output.info('LOW'),
severity: sev === 'critical' ? 'critical' :
sev === 'high' ? 'high' :
sev === 'moderate' || sev === 'medium' ? 'medium' : 'low',
type: 'Dependency CVE',
location: `package.json:${pkg}`,
description: title.substring(0, 35),
@@ -226,7 +270,7 @@ const scanCommand: Command = {
if (pattern.test(lines[i])) {
highCount++;
findings.push({
severity: output.warning('HIGH'),
severity: 'high',
type: 'Hardcoded Secret',
location: `${path.relative(target, fullPath)}:${i + 1}`,
description: type,
@@ -277,7 +321,7 @@ const scanCommand: Command = {
if (severity === 'high') highCount++;
else mediumCount++;
findings.push({
severity: severity === 'high' ? output.warning('HIGH') : output.warning('MEDIUM'),
severity: severity === 'high' ? 'high' : 'medium',
type,
location: `${path.relative(target, fullPath)}:${i + 1}`,
description: desc,
@@ -296,37 +340,59 @@ const scanCommand: Command = {
scanCodeDir(path.resolve(target), scanDepth);
}
spinner.succeed('Scan complete');
if (outputFormat === 'text') spinner.succeed('Scan complete');
// Display results
output.writeln();
if (findings.length > 0) {
output.printTable({
columns: [
{ key: 'severity', header: 'Severity', width: 12 },
{ key: 'type', header: 'Type', width: 18 },
{ key: 'location', header: 'Location', width: 25 },
{ key: 'description', header: 'Description', width: 35 },
],
data: findings.slice(0, 20), // Show first 20
});
if (outputFormat === 'text') {
output.writeln();
if (findings.length > 0) {
output.printTable({
columns: [
{ key: 'severity', header: 'Severity', width: 12 },
{ key: 'type', header: 'Type', width: 18 },
{ key: 'location', header: 'Location', width: 25 },
{ key: 'description', header: 'Description', width: 35 },
],
data: findings.slice(0, 20).map(finding => ({
...finding,
severity: finding.severity === 'critical' ? output.error('CRITICAL') :
finding.severity === 'high' ? output.warning('HIGH') :
finding.severity === 'medium' ? output.warning('MEDIUM') : output.info('LOW'),
})), // Show first 20
});
if (findings.length > 20) {
output.writeln(output.dim(`... and ${findings.length - 20} more issues`));
if (findings.length > 20) {
output.writeln(output.dim(`... and ${findings.length - 20} more issues`));
}
} else {
output.writeln(output.success('No security issues found!'));
}
} else {
output.writeln(output.success('No security issues found!'));
output.writeln();
output.printBox([
`Target: ${target}`,
`Depth: ${depth}`,
`Type: ${scanType}`,
``,
`Critical: ${criticalCount} High: ${highCount} Medium: ${mediumCount} Low: ${lowCount}`,
`Total Issues: ${findings.length}`,
].join('\n'), 'Scan Summary');
}
output.writeln();
output.printBox([
`Target: ${target}`,
`Depth: ${depth}`,
`Type: ${scanType}`,
``,
`Critical: ${criticalCount} High: ${highCount} Medium: ${mediumCount} Low: ${lowCount}`,
`Total Issues: ${findings.length}`,
].join('\n'), 'Scan Summary');
const record = {
timestamp: new Date().toISOString(),
target,
depth,
type: scanType,
summary: {
critical: criticalCount,
high: highCount,
medium: mediumCount,
low: lowCount,
total: findings.length,
},
findings,
};
// Persist the scan result so downstream consumers (the statusline's
// getSecurityStatus in funnel/local-signals.ts, which reads
@@ -335,20 +401,6 @@ const scanCommand: Command = {
try {
const scanDirOut = path.join(path.resolve(target), '.claude', 'security-scans');
fs.mkdirSync(scanDirOut, { recursive: true });
const record = {
timestamp: new Date().toISOString(),
target,
depth,
type: scanType,
summary: {
critical: criticalCount,
high: highCount,
medium: mediumCount,
low: lowCount,
total: findings.length,
},
findings,
};
// Deterministic name keyed on scan config so repeated runs overwrite
// rather than accumulate stale reports.
const outFile = path.join(scanDirOut, `scan-${scanType}-${depth}.json`);
@@ -359,22 +411,25 @@ const scanCommand: Command = {
// Auto-fix if requested
if (fix && criticalCount + highCount > 0) {
output.writeln();
if (outputFormat === 'text') output.writeln();
const fixSpinner = output.createSpinner({ text: 'Attempting to fix vulnerabilities...', spinner: 'dots' });
fixSpinner.start();
if (outputFormat === 'text') fixSpinner.start();
try {
try {
execSync('npm audit fix', { cwd: path.resolve(target), encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
} catch { /* npm audit fix may exit non-zero */ }
fixSpinner.succeed('Applied available fixes (run scan again to verify)');
if (outputFormat === 'text') fixSpinner.succeed('Applied available fixes (run scan again to verify)');
} catch {
fixSpinner.fail('Some fixes could not be applied automatically');
if (outputFormat === 'text') fixSpinner.fail('Some fixes could not be applied automatically');
}
}
if (outputFormat === 'json') output.printJson(record);
else if (outputFormat === 'sarif') output.printJson(scanSarif(findings));
return { success: findings.length === 0 || (criticalCount === 0 && highCount === 0) };
} catch (error) {
spinner.fail('Scan failed');
if (outputFormat === 'text') spinner.fail('Scan failed');
output.printError(`Error: ${error}`);
return { success: false };
}