From 3b4b91fcd5f3b2ac7b215a8b3e441a8db69308b0 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Sat, 10 Oct 2026 17:30:34 +0200 Subject: [PATCH 1/2] fix(security): scan code patterns without the false positives seen on a real tree `ruflo security scan --depth deep` on a 10-repo checkout reported 10 high findings, all false: `child_process.execFile` named in comments, numbered pg placeholders (`$${paramCount}`) as SQL injection, and a Playwright report bundle. Mediums included "retrieval (" read as eval and istanbul/Playwright assets. - eval needs a word start; window.eval still matches. - Command injection is any exec/execSync/execFile use (call, ?.(), .call/.apply/ .bind, ['exec'], passed as a value), except execFile of a literal non-shell program with a literal argv and no shell or options variable. execSync, which `exec[^S]` skipped, is now reported. - A counter-shaped pg placeholder where SQL takes a value, outside SQL quotes, is not interpolation; quoted or value-shaped `$${...}` still is. The SQL test runs in linear time. - Comment text is stripped before matching (strings respected); a block comment carries only from a line-start opener that closes later. - istanbul prettify/sorter/block-navigation/lcov-report next to a coverage marker, and Playwright trace/data next to index.html, are skipped. Folder names are looked up in a Map. Co-Authored-By: Ruflo & AQE Claude-Session: https://claude.ai/code/session_01CGoza3gyxBjpaiMPhGHcHs --- .../security-scan-code-patterns.test.ts | 202 ++++++++++++++++++ .../src/commands/security-code-patterns.ts | 150 +++++++++++++ v3/@claude-flow/cli/src/commands/security.ts | 19 +- 3 files changed, 359 insertions(+), 12 deletions(-) create mode 100644 v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts create mode 100644 v3/@claude-flow/cli/src/commands/security-code-patterns.ts diff --git a/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts b/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts new file mode 100644 index 0000000000..3f497f8548 --- /dev/null +++ b/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts @@ -0,0 +1,202 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import type { CommandContext } from '../src/types.js'; + +vi.mock('../src/output.js', () => ({ + output: { + writeln: () => {}, printJson: () => {}, printTable: () => {}, printBox: () => {}, printError: () => {}, printWarning: () => {}, + bold: (v: string) => v, dim: (v: string) => v, success: (v: string) => v, error: (v: string) => v, warning: (v: string) => v, info: (v: string) => v, + createSpinner: () => ({ start: () => {}, setText: () => {}, succeed: () => {}, fail: () => {} }), + }, +})); + +import { securityCommand } from '../src/commands/security.js'; + +const scan = securityCommand.subcommands!.find(command => command.name === 'scan')!; +let target: string; + +type Finding = { severity: string; type: string; location: string }; + +async function findings(files: Record): Promise { + for (const [name, body] of Object.entries(files)) { + mkdirSync(join(target, name, '..'), { recursive: true }); + writeFileSync(join(target, name), body); + } + const ctx: CommandContext = { args: [], flags: { _: [], target, depth: 'standard', type: 'code', output: 'json' }, cwd: target, interactive: false }; + await scan.action!(ctx); + return JSON.parse(readFileSync(join(target, '.claude/security-scans/scan-code-standard.json'), 'utf8')).findings; +} + +const types = (rows: Finding[]) => rows.map(row => `${row.type} ${row.location}`).sort(); + +beforeEach(() => { target = mkdtempSync(join(tmpdir(), 'ruflo-scan-patterns-')); }); +afterEach(() => { rmSync(target, { recursive: true, force: true }); }); + +describe('security scan code patterns: false positives seen on a real tree', () => { + it('does not report eval inside a longer word such as "retrieval ("', async () => { + expect(await findings({ 'copy.ts': 'export const label = "Memory + retrieval (vector) and private inference";\n' })).toEqual([]); + }); + + it('does not report execFile, or child_process named in comments and messages, as command injection', async () => { + expect(await findings({ + 'discovery.ts': [ + '// TailscaleDiscovery only needs Node built-ins (`child_process.execFile`),', + '/**', + ' * No new dependency: shells out via `node:child_process.execFile`,', + ' */', + "const { execFile } = require('child_process'); execFile('tailscale', ['status', '--json']);", + 'throw new Error("child_process.exec must never be called by a blocked stub");', + ].join('\n'), + })).toEqual([]); + }); + + it('does not report a numbered SQL placeholder ($${n}) as SQL injection', async () => { + expect(await findings({ + 'store.js': [ + ' sql += ` AND t.category_id = $${paramCount}`;', + ' sql += ` ORDER BY text_score DESC LIMIT $${paramCount + 1}`;', + ].join('\n'), + })).toEqual([]); + }); + + it('skips generated coverage and Playwright report bundles, known by their marker files', async () => { + expect(await findings({ + 'coverage/coverage-final.json': '{}', + 'coverage/prettify.js': 'el.innerHTML = html;\n', + 'e2e/playwright-report/index.html': '', + 'e2e/playwright-report/trace/assets/view.js': 'node.innerHTML = s; eval(x);\n', + })).toEqual([]); + }); + + it('does not report a URL or a pattern inside a string as a comment boundary', async () => { + expect(await findings({ 'u.ts': "const u = 'http://x/*'; const v = 1;\n" })).toEqual([]); + }); +}); + +describe('security scan code patterns: real findings still reported', () => { + it('reports eval calls, including window.eval', async () => { + expect(types(await findings({ 'a.ts': 'eval(userInput);\nwindow.eval(bundle);\n' }))).toEqual(['Eval Usage a.ts:1', 'Eval Usage a.ts:2']); + }); + + it('reports exec and execSync called through child_process', async () => { + expect(types(await findings({ + 'b.ts': "require('child_process').exec(`ls ${dir}`);\nchild_process.execSync(cmd);\n", + }))).toEqual(['Command Injection b.ts:1', 'Command Injection b.ts:2']); + }); + + it('reports an interpolated value in SQL, also next to a placeholder', async () => { + expect(types(await findings({ + 'c.ts': 'const sql = `SELECT * FROM users WHERE id = ${id}`;\nsql += ` AND a = $${n} AND b = ${name}`;\n', + }))).toEqual(['SQL Injection c.ts:1', 'SQL Injection c.ts:2']); + }); + + it('reports innerHTML and dangerouslySetInnerHTML in source', async () => { + expect(types(await findings({ 'src/d.tsx': 'el.innerHTML = html;\n
\n' }))) + .toEqual(['React XSS src/d.tsx:2', 'innerHTML src/d.tsx:1']); + }); +}); + +describe('security scan code patterns: shapes the narrowing must not hide', () => { + it('scans code that shares a line with a comment, a generator method and JSX continuation lines', async () => { + expect(types(await findings({ + 'e.tsx': [ + '/* route */ eval(userInput);', + '/* start', + ' end */ eval(userInput);', + 'class A { * run() { eval(userInput); } }', + ' * ', + 'const x = 1 // eval(commented)', + ].join('\n'), + }))).toEqual(['Eval Usage e.tsx:1', 'Eval Usage e.tsx:3', 'Eval Usage e.tsx:4', 'React XSS e.tsx:5']); + }); + + it('reports execFile handed a shell, and exec through call/apply', async () => { + expect(types(await findings({ + 'f.ts': [ + "require('child_process').execFile('sh', ['-c', userInput]);", + "require('child_process').execFile('echo', [userInput], { shell: true });", + "require('child_process').exec.call(null, userInput);", + "require('child_process').exec/*why*/(userInput);", + "require('child_process').execFile('git', ['status'], { shell: false });", + "require('child_process').execFile('/bin/sh', ['-c', input]);", + "require('child_process').execFile.call(null, 'sh', ['-c', input]);", + "require('child_process').execFile('echo', [input], {'shell': true});", + "require('child_process').exec?.(input);", + "require('child_process')['exec'](input);", + "const cp = require('child_process'); cp.exec(input); cp.execFile('git', ['status']);", + ].join('\n'), + }))).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(n => `Command Injection f.ts:${n}`).sort()); + }); + + it('keeps a /* inside a regex or JSX text from hiding the lines after it', async () => { + expect(types(await findings({ + 'h.tsx': "const r = /[/*]/;\neval(input);\nconst v =

don't

; const s = '/*';\neval(input);\n", + }))).toEqual(['Eval Usage h.tsx:2', 'Eval Usage h.tsx:4']); + }); + + it('reports a $${value} that is quoted or not counter-shaped, as SQL injection', async () => { + expect(types(await findings({ + 'g.ts': [ + "const sql = `SELECT * FROM users WHERE name = '$${userInput}'`;", + 'const sql2 = `SELECT * FROM t WHERE id = $${userInput}`;', + "const sql3 = `SELECT * FROM users WHERE name = 'prefix $${discount} suffix'`;", + 'const sql4 = `SELECT * FROM t WHERE id = $${amount}`;', + ].join('\n'), + }))).toEqual(['SQL Injection g.ts:1', 'SQL Injection g.ts:2', 'SQL Injection g.ts:3', 'SQL Injection g.ts:4']); + }); + + it('still scans source in a folder named coverage, with or without report markers', async () => { + expect(types(await findings({ + 'src/coverage/handler.ts': 'eval(userInput);\n', + 'coverage/lcov.info': '', + 'coverage/handler.ts': 'eval(userInput);\n', + 'playwright-report/index.html': '', + 'playwright-report/handler.ts': 'eval(userInput);\n', + }))).toEqual(['Eval Usage coverage/handler.ts:1', 'Eval Usage playwright-report/handler.ts:1', 'Eval Usage src/coverage/handler.ts:1']); + }); + + it('scans a folder named constructor or __proto__', async () => { + expect(types(await findings({ 'constructor/a.ts': 'eval(input);\n', '__proto__/b.ts': 'eval(input);\n' }))) + .toEqual(['Eval Usage __proto__/b.ts:1', 'Eval Usage constructor/a.ts:1']); + }); + + it('keeps a line-start /* in JSX text, never closed, from hiding the lines after it', async () => { + expect(types(await findings({ + 'j.tsx': "const view =

\n/*\n

;\neval(input);\nrequire('child_process').exec(input);\n", + }))).toEqual(['Command Injection j.tsx:5', 'Eval Usage j.tsx:4']); + }); + + it('reports a counter placeholder inside SQL quotes, wherever the quote count lands', async () => { + expect(types(await findings({ + 'k.ts': [ + 'const label = "\'"; const sql = `SELECT \'$${paramCount}\'`;', + 'const sql = `SELECT "$${paramCount}" FROM t`;', + "const sql = `SELECT * FROM t WHERE name = 'prefix = $${paramCount} suffix'`;", + ].join('\n'), + }))).toEqual(['SQL Injection k.ts:1', 'SQL Injection k.ts:2', 'SQL Injection k.ts:3']); + }); + + it('reports execFile given an options variable, a chained argv, or exec passed around as a value', async () => { + expect(types(await findings({ + 'm.ts': [ + "require('child_process').execFile('echo', [input], options);", + "require('child_process').execFile('git', ['status'].concat(input));", + "module.exports = require('child_process').exec;", + "require('child_process').execFile('git', ['status'], (err, out) => done(out));", + "require('child_process').execFile('git', ['status'], (options));", + "require('child_process').execFile('git', ['status'], { ...options });", + "const run = require('child_process').exec || fallback;", + "const cp = require('child_process'); const run = cp.exec; cp.execFile('git', ['status']);", + ].join('\n'), + }))).toEqual([1, 2, 3, 5, 6, 7, 8].map(n => `Command Injection m.ts:${n}`)); + }); + + it('scans a long minified line in linear time', async () => { + const started = Date.now(); + await findings({ 'min.js': `const s = "${'$$" + "{'.repeat(32_000)}"; const sql = 1;\n` }); + expect(Date.now() - started).toBeLessThan(1_000); + }); +}); + diff --git a/v3/@claude-flow/cli/src/commands/security-code-patterns.ts b/v3/@claude-flow/cli/src/commands/security-code-patterns.ts new file mode 100644 index 0000000000..4c1c529f2f --- /dev/null +++ b/v3/@claude-flow/cli/src/commands/security-code-patterns.ts @@ -0,0 +1,150 @@ +/** + * Line patterns for `security scan` phase 3, and what each line is tested on. + * + * The patterns are a heuristic, so each one is narrowed only where a false positive was seen on a real tree, and only + * by a shape that is safe on its face: + * - eval needs a word start: "retrieval (" in prose is not a call; `window.eval(` still is. + * - command injection is any exec, execSync or execFile use (a call, `?.(`, `.call`/`.apply`/`.bind`, `['exec']`), + * except execFile of a literal non-shell program with a literal argv array and no `shell` key on the line. The old + * `exec[^S]` matched every execFile and the word in comments, and skipped execSync. + * - a pg placeholder `$${paramCount + 1}` is a parameter number, not a value in the SQL text. Exempt only when the + * expression is a number, a loop letter, an `.length`, or a name ending in Count/Index/Idx/Num/Pos, and the + * placeholder is not inside a quoted SQL string; `'$${name}'`, `$${userInput}` and `'x $${discount} y'` are reported. + * - comment text is removed before matching, not whole lines: code after a closing `*` + `/`, a generator method + * `* run()` and JSX continuation lines are still scanned. + */ + +export type CodePattern = { + /** Tested on one comment-stripped line. */ + match: (line: string) => boolean + type: string + severity: 'high' | 'medium' + desc: string +} + +/** No `g` flag, so `test` keeps no lastIndex between lines. */ +const re = (pattern: RegExp) => (line: string) => pattern.test(line) + +const SHELL_PROGRAM = /^(?:.*[\\/])?(?:sh|bash|zsh|dash|ksh|fish|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh)$/i +// Every use of an exec function on a line, as a call or a value; `{ execFile }` in a destructure is a name, not a use. +const EXEC_ANY = /\bexec\w*\b(?!\s*[A-Za-z_$}:,])|\[\s*['"`]exec/g +const EXEC_USE = /child_process.*(?:\bexec(?:Sync|File|FileSync)?\b\s*(?:\(|\?\.\s*\(|\.(?:call|apply|bind)\b)|\[\s*['"`]exec\w*['"`]\s*\]|\.exec(?:Sync|File|FileSync)?\b(?!\s*[A-Za-z_$]))/ +// A literal program, a literal argv array (nothing chained on it), then the end of the call, an options object literal +// with no computed key, or a callback. An options variable could carry `shell: true`, so it is not plain. +const PLAIN_EXEC_FILE = /\bexecFile(?:Sync)?\s*\(\s*(['"`])([^'"`$]+)\1\s*,\s*\[[^\][]*\]\s*(?:\)|,\s*\{(?:(?!\.\.\.)[^{}[\]])*\}\s*[,)]|,\s*(?:\((?:\s*[A-Za-z_$][\w$]*\s*,?)*\)\s*=>|function\b|async\b|[A-Za-z_$][\w$]*\s*=>))/ + +/** execFile of a literal, non-shell program with a literal argv array, and no `shell` anywhere on the line. */ +const isPlainExecFile = (line: string): boolean => { + const call = PLAIN_EXEC_FILE.exec(line) + if (call === null || /shell/i.test(line) || SHELL_PROGRAM.test(call[2])) return false + // Every exec use on the line must be that one call: `exec(x); execFile('git', [...])` is still reported. + return (line.match(EXEC_ANY) ?? []).length === 1 +} + +const commandInjection = (line: string): boolean => EXEC_USE.test(line) && !isPlainExecFile(line) + +const COUNTER = /^\s*(?:\d+|[ijkn]|[\w$.]+\.length|(?:[A-Za-z_$][\w$]*[a-z0-9])?(?:Count|Index|Idx|Num|Pos)|count|index|idx|num|pos)\s*(?:[+-]\s*\d+\s*)?$/ +// Where a pg parameter stands in SQL: after a comparison, a list or call opener, or a clause keyword. +const PARAM_BEFORE = /(?:[=<>(,]|\b(?:LIMIT|OFFSET|IN|VALUES|BETWEEN|AND|OR|LIKE|ILIKE|SET|BY|THEN|ELSE|WHEN|IS))\s*$/i +const PARAM_AFTER = /^(?:\s|[,);]|::|$|`)/ + +/** + * `$${paramCount}` / `LIMIT $${params.length + 1}`: the pg parameter number where SQL takes a value, not interpolated + * SQL text. `'$${n}'`, `"$${n}"`, `$${userInput}` and `x $${discount}` keep their interpolation. + */ +export const withoutPlaceholders = (line: string): string => + line.replace(/\$\$\{([^}]*)\}/g, (match, expr: string, at: number) => + COUNTER.test(expr) && PARAM_BEFORE.test(line.slice(Math.max(0, at - 16), at)) && PARAM_AFTER.test(line.slice(at + match.length)) && !inSqlQuote(line, at) ? '' : match) + +/** An odd count of `'` between the template literal's opening backtick and `at`: inside a quoted SQL string. */ +const inSqlQuote = (line: string, at: number): boolean => + (line.slice(line.lastIndexOf('`', at) + 1, at).match(/'/g) ?? []).length % 2 === 1 + +/** The old `/\$\{.*\}.*sql|sql.*\$\{/i`, in linear time: a long minified line made the regex quadratic. */ +const sqlInterpolation = (line: string): boolean => { + const lower = line.toLowerCase() + const open = line.indexOf('${') + const close = open < 0 ? -1 : line.indexOf('}', open + 2) + if (close >= 0 && lower.indexOf('sql', close + 1) >= 0) return true + const sql = lower.indexOf('sql') + return sql >= 0 && line.indexOf('${', sql + 3) >= 0 +} + +export const CODE_PATTERNS: readonly CodePattern[] = [ + { match: re(/(? sqlInterpolation(line) && sqlInterpolation(withoutPlaceholders(line)), type: 'SQL Injection', severity: 'high', desc: 'Possible SQL injection' }, +] + +/** + * The file's lines with comment text blanked (line count kept, so locations stay right). Strings are respected, so + * `'http://x'` is not a comment; a template literal may span lines. Regex literals and JSX text are not parsed, so a + * `//` or `/*` inside one is taken as a comment. That can only hide the rest of that one line: a block comment carries + * to the next lines only when its `/*` starts the line, which a regex or JSX text never does. + */ +export function codeLinesOf(content: string): string[] { + const out: string[] = [] + let inBlock = false + let inTemplate = false + + let offset = 0 + + for (const line of content.split('\n')) { + let code = '' + let quote: string | null = inTemplate ? '`' : null + let carries = inBlock + + for (let i = 0; i < line.length; i++) { + const ch = line[i] + const next = line[i + 1] + + if (inBlock) { + if (ch === '*' && next === '/') { inBlock = false; i++; code += ' ' } + continue + } + if (ch === '\\') { code += ch + (next ?? ''); i++; continue } + if (quote !== null) { + if (ch === quote) quote = null + code += ch + continue + } + if (ch === '/' && next === '/') break + if (ch === '/' && next === '*') { + inBlock = true + // Carried past this line only from a line-start opener that is closed later in the file: JSX text or a regex + // never starts a line with an unclosed comment, so neither can blank the lines after it. + carries = code.trim() === '' && content.indexOf('*/', offset + i + 2) >= 0 + i++ + code += ' ' + continue + } + if (ch === '"' || ch === "'" || ch === '`') quote = ch + code += ch + } + + if (inBlock && !carries) inBlock = false + inTemplate = quote === '`' + out.push(code) + offset += line.length + 1 + } + + return out +} + +/** + * Generated report assets, named by what the report writes, inside a folder its marker file identifies. Only those + * entries are skipped: other files in a folder that merely shares the name are still scanned. + */ +const REPORT_ASSETS = new Map }>([ + ['coverage', { markers: ['coverage-final.json', 'lcov.info', 'clover.xml'], assets: new Set(['prettify.js', 'sorter.js', 'block-navigation.js', 'lcov-report']) }], + ['playwright-report', { markers: ['index.html'], assets: new Set(['trace', 'data']) }], +]) + +/** True for an istanbul or Playwright asset, given its parent folder's name and what the parent folder holds. */ +export function isGeneratedReportAsset(parentName: string, entryName: string, parentHas: (name: string) => boolean): boolean { + // A Map, so a folder named `constructor` or `__proto__` is not looked up on Object.prototype. + const report = REPORT_ASSETS.get(parentName) + return report !== undefined && report.assets.has(entryName) && report.markers.some(parentHas) +} diff --git a/v3/@claude-flow/cli/src/commands/security.ts b/v3/@claude-flow/cli/src/commands/security.ts index 70bb75162a..c765e3f19e 100644 --- a/v3/@claude-flow/cli/src/commands/security.ts +++ b/v3/@claude-flow/cli/src/commands/security.ts @@ -11,6 +11,7 @@ import { execSync } from 'node:child_process'; import { existsSync, statSync } from 'node:fs'; import { resolve as resolvePath } from 'node:path'; import { createBuiltinAIDefence, type DefenceEngine } from '../security/builtin-aidefence.js'; +import { CODE_PATTERNS, codeLinesOf, isGeneratedReportAsset } from './security-code-patterns.js'; // Accepted values for `security scan`'s enum flags — the single source of truth // for both validation and the traversal-depth maps below. @@ -292,14 +293,7 @@ const scanCommand: Command = { // Phase 3: Check for common security issues in code if ((scanType === 'all' || scanType === 'code') && depth !== 'quick') { spinner.setText('Analyzing code patterns...'); - const codePatterns = [ - { pattern: /eval\s*\(/g, type: 'Eval Usage', severity: 'medium', desc: 'eval() can execute arbitrary code' }, - { pattern: /innerHTML\s*=/g, type: 'innerHTML', severity: 'medium', desc: 'XSS risk with innerHTML' }, - { pattern: /dangerouslySetInnerHTML/g, type: 'React XSS', severity: 'medium', desc: 'React XSS risk' }, - { pattern: /child_process.*exec[^S]/g, type: 'Command Injection', severity: 'high', desc: 'Possible command injection' }, - { pattern: /\$\{.*\}.*sql|sql.*\$\{/gi, type: 'SQL Injection', severity: 'high', desc: 'Possible SQL injection' }, - ]; - + // The patterns, and the comment stripping they are tested after, live in security-code-patterns.ts. const scanCodeDir = (dir: string, depthLimit: number) => { // Positive-test rather than `<= 0`: undefined and NaN both fail this, // so a bad budget stops the recursion instead of disabling the limiter. @@ -309,15 +303,17 @@ const scanCommand: Command = { for (const entry of entries) { if (entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dist') continue; const fullPath = path.join(dir, entry.name); + // Coverage and Playwright report assets bundle third-party code (prettify, CodeMirror, React), not the project's. + if (isGeneratedReportAsset(path.basename(dir), entry.name, name => fs.existsSync(path.join(dir, name)))) continue; if (entry.isDirectory()) { scanCodeDir(fullPath, depthLimit - 1); } else if (entry.isFile() && /\.(ts|js|tsx|jsx)$/.test(entry.name) && !entry.name.endsWith('.d.ts')) { try { const content = fs.readFileSync(fullPath, 'utf-8'); - const lines = content.split('\n'); + const lines = codeLinesOf(content); for (let i = 0; i < lines.length; i++) { - for (const { pattern, type, severity, desc } of codePatterns) { - if (pattern.test(lines[i])) { + for (const { match, type, severity, desc } of CODE_PATTERNS) { + if (match(lines[i])) { if (severity === 'high') highCount++; else mediumCount++; findings.push({ @@ -326,7 +322,6 @@ const scanCommand: Command = { location: `${path.relative(target, fullPath)}:${i + 1}`, description: desc, }); - pattern.lastIndex = 0; } } } From 58604dabcee02911c8d77e15516d71157b94a369 Mon Sep 17 00:00:00 2001 From: Dragan Spiridonov Date: Sat, 10 Oct 2026 18:13:04 +0200 Subject: [PATCH 2/2] fix(security): keep the old command-injection reach; bound the comment stripper Adversarial review of the first commit (a Claude devil's-advocate agent and three Codex rounds) found inputs main reports that it dropped, a ReDoS, and quadratic paths. - Command injection is main's rule again (child_process ... exec), tested after comment stripping, so execSync is reported and no execFile shape is exempt: env, node -e, python -c, bash.exe, options variables and exec passed as a value were all bypasses. The execFile callback regex that backtracked catastrophically is gone. - Carried block comments continue only through comment-looking lines; regex literals are read as code (bounded to 200 chars); '://' is never a comment. Lines are built from parts with a 12-char tail, so the stripper is linear. - SQL placeholders: only param/placeholder names, params/values/args.length, numbers and loop letters, in value position, outside single- or double-quoted SQL text, in one left-to-right pass that skips escapes. pageNum, userIdx, req.body.length and quoted placeholders are reported. - Spec: 26 tests, including every reviewer input and linear-time checks; each of ten source mutations fails at least one test. Co-Authored-By: Ruflo & AQE Claude-Session: https://claude.ai/code/session_01CGoza3gyxBjpaiMPhGHcHs --- .../security-scan-code-patterns.test.ts | 133 +++++++++++++---- .../src/commands/security-code-patterns.ts | 135 +++++++++++------- 2 files changed, 184 insertions(+), 84 deletions(-) diff --git a/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts b/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts index 3f497f8548..2c66640822 100644 --- a/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts +++ b/v3/@claude-flow/cli/__tests__/security-scan-code-patterns.test.ts @@ -39,15 +39,13 @@ describe('security scan code patterns: false positives seen on a real tree', () expect(await findings({ 'copy.ts': 'export const label = "Memory + retrieval (vector) and private inference";\n' })).toEqual([]); }); - it('does not report execFile, or child_process named in comments and messages, as command injection', async () => { + it('does not report child_process.execFile named in comments as command injection', async () => { expect(await findings({ 'discovery.ts': [ '// TailscaleDiscovery only needs Node built-ins (`child_process.execFile`),', '/**', ' * No new dependency: shells out via `node:child_process.execFile`,', ' */', - "const { execFile } = require('child_process'); execFile('tailscale', ['status', '--json']);", - 'throw new Error("child_process.exec must never be called by a blocked stub");', ].join('\n'), })).toEqual([]); }); @@ -57,6 +55,7 @@ describe('security scan code patterns: false positives seen on a real tree', () 'store.js': [ ' sql += ` AND t.category_id = $${paramCount}`;', ' sql += ` ORDER BY text_score DESC LIMIT $${paramCount + 1}`;', + ' const q = `SELECT * FROM t WHERE id IN ($${params.length}, $${values.length + 1})`;', ].join('\n'), })).toEqual([]); }); @@ -112,22 +111,26 @@ describe('security scan code patterns: shapes the narrowing must not hide', () = }))).toEqual(['Eval Usage e.tsx:1', 'Eval Usage e.tsx:3', 'Eval Usage e.tsx:4', 'React XSS e.tsx:5']); }); - it('reports execFile handed a shell, and exec through call/apply', async () => { - expect(types(await findings({ - 'f.ts': [ - "require('child_process').execFile('sh', ['-c', userInput]);", - "require('child_process').execFile('echo', [userInput], { shell: true });", - "require('child_process').exec.call(null, userInput);", - "require('child_process').exec/*why*/(userInput);", - "require('child_process').execFile('git', ['status'], { shell: false });", - "require('child_process').execFile('/bin/sh', ['-c', input]);", - "require('child_process').execFile.call(null, 'sh', ['-c', input]);", - "require('child_process').execFile('echo', [input], {'shell': true});", - "require('child_process').exec?.(input);", - "require('child_process')['exec'](input);", - "const cp = require('child_process'); cp.exec(input); cp.execFile('git', ['status']);", - ].join('\n'), - }))).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(n => `Command Injection f.ts:${n}`).sort()); + it('reports every exec use the old rule reported, execFile included, as command injection', async () => { + const lines = [ + "require('child_process').execFile('sh', ['-c', userInput]);", + "require('child_process').execFile('echo', [userInput], { shell: true });", + "require('child_process').exec.call(null, userInput);", + "require('child_process').exec/*why*/(userInput);", + "require('child_process').execFile('/usr/bin/env', ['sh', '-c', userCmd]);", + "require('child_process').execFile('node', ['-e', userCode]);", + "require('child_process').execFileSync('bash.exe', ['-c', userCmd]);", + "require('child_process').exec?.(input);", + "require('child_process')['exec'](input);", + "module.exports = require('child_process').exec;", + "(require('child_process').exec as any)(cmd);", + "const { exec } = require('child_process'); const run = promisify(exec);", + "const { exec, execFile } = require('child_process'); register(exec, 1); execFile('git', ['status']);", + "const {exec} = require('child_process'); Reflect.apply(exec, null, [input]);", + "require('child_process').execFile('git', ['status'], (a = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx') => a);", + ]; + expect(types(await findings({ 'f.ts': lines.join('\n') }))) + .toEqual(lines.map((_, i) => `Command Injection f.ts:${i + 1}`).sort()); }); it('keeps a /* inside a regex or JSX text from hiding the lines after it', async () => { @@ -178,19 +181,89 @@ describe('security scan code patterns: shapes the narrowing must not hide', () = }))).toEqual(['SQL Injection k.ts:1', 'SQL Injection k.ts:2', 'SQL Injection k.ts:3']); }); - it('reports execFile given an options variable, a chained argv, or exec passed around as a value', async () => { + it('keeps a backtick misread in a regex or JSX from hiding later lines through a template /*', async () => { expect(types(await findings({ - 'm.ts': [ - "require('child_process').execFile('echo', [input], options);", - "require('child_process').execFile('git', ['status'].concat(input));", - "module.exports = require('child_process').exec;", - "require('child_process').execFile('git', ['status'], (err, out) => done(out));", - "require('child_process').execFile('git', ['status'], (options));", - "require('child_process').execFile('git', ['status'], { ...options });", - "const run = require('child_process').exec || fallback;", - "const cp = require('child_process'); const run = cp.exec; cp.execFile('git', ['status']);", + 'n.tsx': [ + 'const Q = /[`]/;', + 'const t = `', + '/* text', + '`;', + 'eval(userInput);', + "require('child_process').exec(userCmd);", + "const glob = '**/*.ts';", + 'fetch(`https://api.example.com/${id}`); eval(userInput);', ].join('\n'), - }))).toEqual([1, 2, 3, 5, 6, 7, 8].map(n => `Command Injection m.ts:${n}`)); + }))).toEqual(['Command Injection n.tsx:6', 'Eval Usage n.tsx:5', 'Eval Usage n.tsx:8']); + }); + + it('reports a counter placeholder that is not where SQL takes a value, or not param-named', async () => { + expect(types(await findings({ + 'p.ts': [ + 'const sql = `SELECT x$${paramCount} FROM t`;', + 'const sql = `SELECT * FROM t WHERE id = $${paramCount}abc`;', + 'const sql = `SELECT * FROM t OFFSET $${pageNum}`;', + 'const sql = `SELECT * FROM t WHERE id = $${userIdx}`;', + 'const sql = `UPDATE t SET a = $${req.body.length}`;', + ].join('\n'), + }))).toEqual([1, 2, 3, 4, 5].map(n => `SQL Injection p.ts:${n}`)); + }); + + it('scans report-named assets when their marker file is absent', async () => { + expect(types(await findings({ + 'coverage/prettify.js': 'el.innerHTML = html;\n', + 'playwright-report/trace/view.js': 'eval(x);\n', + }))).toEqual(['Eval Usage playwright-report/trace/view.js:1', 'innerHTML coverage/prettify.js:1']); + }); + + it('reads a regex literal as code, so a // or /* or backtick inside it hides nothing', async () => { + expect(types(await findings({ + 'r.ts': [ + 'const r = /[//]/; eval(input);', + 'const s = /[/*]/; eval(input);', + 'const Q = /[`]/;', + 'const t = `', + '/*', + '* ${eval(input)}', + '`;', + 'const half = a / b; eval(input); // eval(commented)', + ].join('\n'), + }))).toEqual(['Eval Usage r.ts:1', 'Eval Usage r.ts:2', 'Eval Usage r.ts:6', 'Eval Usage r.ts:8']); + }); + + it('keeps a URL after a backtick misread in JSX text from blanking the rest of its line', async () => { + expect(types(await findings({ + 'k.tsx': 'const v = `;\nfetch(`https://api.example.com/${id}`); eval(input);\n', + }))).toEqual(['Eval Usage k.tsx:2']); + }); + + it('reports a counter placeholder inside double-quoted SQL text, or after an escaped backtick in quotes', async () => { + expect(types(await findings({ + 'q.ts': [ + 'const sql = `SELECT "x = $${paramCount} y" FROM t`;', + "const sql = `SELECT 'x \\` = $${paramCount} y' FROM t`;", + 'const sql = `SELECT * FROM t WHERE id = $${userargs.length}`;', + ].join('\n'), + }))).toEqual(['SQL Injection q.ts:1', 'SQL Injection q.ts:2', 'SQL Injection q.ts:3']); + }); + + it('stays linear on lines of comment openers, placeholders and regex starts', async () => { + const started = Date.now(); + await findings({ + 'long.js': [ + 'x; /* */'.repeat(16_000), + 'const sql = `SELECT ' + Array(8_000).fill('$${paramCount}').join(', ') + '`;', + '(/'.repeat(16_000), + '[/'.repeat(16_000), + 'x / '.repeat(64_000) + 'z', + ].join('\n'), + }); + expect(Date.now() - started).toBeLessThan(1_000); + }); + + it('scans many unclosed line-start comment openers in linear time', async () => { + const started = Date.now(); + await findings({ 'open.js': '/* x\n'.repeat(40_000) + 'eval(input);\n' }); + expect(Date.now() - started).toBeLessThan(1_000); }); it('scans a long minified line in linear time', async () => { diff --git a/v3/@claude-flow/cli/src/commands/security-code-patterns.ts b/v3/@claude-flow/cli/src/commands/security-code-patterns.ts index 4c1c529f2f..9a0e160aae 100644 --- a/v3/@claude-flow/cli/src/commands/security-code-patterns.ts +++ b/v3/@claude-flow/cli/src/commands/security-code-patterns.ts @@ -1,17 +1,16 @@ /** * Line patterns for `security scan` phase 3, and what each line is tested on. * - * The patterns are a heuristic, so each one is narrowed only where a false positive was seen on a real tree, and only - * by a shape that is safe on its face: - * - eval needs a word start: "retrieval (" in prose is not a call; `window.eval(` still is. - * - command injection is any exec, execSync or execFile use (a call, `?.(`, `.call`/`.apply`/`.bind`, `['exec']`), - * except execFile of a literal non-shell program with a literal argv array and no `shell` key on the line. The old - * `exec[^S]` matched every execFile and the word in comments, and skipped execSync. - * - a pg placeholder `$${paramCount + 1}` is a parameter number, not a value in the SQL text. Exempt only when the - * expression is a number, a loop letter, an `.length`, or a name ending in Count/Index/Idx/Num/Pos, and the - * placeholder is not inside a quoted SQL string; `'$${name}'`, `$${userInput}` and `'x $${discount} y'` are reported. - * - comment text is removed before matching, not whole lines: code after a closing `*` + `/`, a generator method - * `* run()` and JSX continuation lines are still scanned. + * The patterns are a heuristic. Each is narrowed only where a false positive was seen on a real tree, and only by a + * shape that cannot carry the risk the rule looks for: + * - every rule is tested after comment text is blanked, so a comment naming `child_process.execFile` or `eval(` is + * not a finding; + * - eval needs a word start: "retrieval (" in prose is not a call; `eval(` and `window.eval(` still are; + * - command injection keeps the old rule's reach (any `exec` after `child_process` on the line), and no longer skips + * execSync as `exec[^S]` did; + * - a pg placeholder such as `$${paramCount + 1}` is a parameter number, not a value in the SQL text. It is exempt only + * when its expression is a number, a loop letter, `params.length`-style, or a name containing `param` or `placeholder`, it + * stands where SQL takes a value, and it is not inside a quoted SQL string. */ export type CodePattern = { @@ -25,40 +24,37 @@ export type CodePattern = { /** No `g` flag, so `test` keeps no lastIndex between lines. */ const re = (pattern: RegExp) => (line: string) => pattern.test(line) -const SHELL_PROGRAM = /^(?:.*[\\/])?(?:sh|bash|zsh|dash|ksh|fish|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh)$/i -// Every use of an exec function on a line, as a call or a value; `{ execFile }` in a destructure is a name, not a use. -const EXEC_ANY = /\bexec\w*\b(?!\s*[A-Za-z_$}:,])|\[\s*['"`]exec/g -const EXEC_USE = /child_process.*(?:\bexec(?:Sync|File|FileSync)?\b\s*(?:\(|\?\.\s*\(|\.(?:call|apply|bind)\b)|\[\s*['"`]exec\w*['"`]\s*\]|\.exec(?:Sync|File|FileSync)?\b(?!\s*[A-Za-z_$]))/ -// A literal program, a literal argv array (nothing chained on it), then the end of the call, an options object literal -// with no computed key, or a callback. An options variable could carry `shell: true`, so it is not plain. -const PLAIN_EXEC_FILE = /\bexecFile(?:Sync)?\s*\(\s*(['"`])([^'"`$]+)\1\s*,\s*\[[^\][]*\]\s*(?:\)|,\s*\{(?:(?!\.\.\.)[^{}[\]])*\}\s*[,)]|,\s*(?:\((?:\s*[A-Za-z_$][\w$]*\s*,?)*\)\s*=>|function\b|async\b|[A-Za-z_$][\w$]*\s*=>))/ - -/** execFile of a literal, non-shell program with a literal argv array, and no `shell` anywhere on the line. */ -const isPlainExecFile = (line: string): boolean => { - const call = PLAIN_EXEC_FILE.exec(line) - if (call === null || /shell/i.test(line) || SHELL_PROGRAM.test(call[2])) return false - // Every exec use on the line must be that one call: `exec(x); execFile('git', [...])` is still reported. - return (line.match(EXEC_ANY) ?? []).length === 1 -} - -const commandInjection = (line: string): boolean => EXEC_USE.test(line) && !isPlainExecFile(line) - -const COUNTER = /^\s*(?:\d+|[ijkn]|[\w$.]+\.length|(?:[A-Za-z_$][\w$]*[a-z0-9])?(?:Count|Index|Idx|Num|Pos)|count|index|idx|num|pos)\s*(?:[+-]\s*\d+\s*)?$/ +// A `.length` counts only on a param-, value- or arg-named array: `req.body.length` is whatever the client sent. +const COUNTER = /^\s*(?:\d+|[ijkn]|(?:[A-Za-z_$][\w$]*(?:Params?|Placeholders?|Values?|Args?)|params?|placeholders?|values?|args?)\.length|[A-Za-z_$]*(?:[Pp]aram|[Pp]laceholder)[\w$]*)\s*(?:[+-]\s*\d+\s*)?$/ // Where a pg parameter stands in SQL: after a comparison, a list or call opener, or a clause keyword. const PARAM_BEFORE = /(?:[=<>(,]|\b(?:LIMIT|OFFSET|IN|VALUES|BETWEEN|AND|OR|LIKE|ILIKE|SET|BY|THEN|ELSE|WHEN|IS))\s*$/i const PARAM_AFTER = /^(?:\s|[,);]|::|$|`)/ /** * `$${paramCount}` / `LIMIT $${params.length + 1}`: the pg parameter number where SQL takes a value, not interpolated - * SQL text. `'$${n}'`, `"$${n}"`, `$${userInput}` and `x $${discount}` keep their interpolation. + * SQL text. `'$${n}'`, `"$${n}"`, `$${userInput}` and `x $${discount}` keep their interpolation. One left-to-right + * pass: quotes are counted since the last backtick, so a placeholder inside a quoted SQL string keeps its finding. */ -export const withoutPlaceholders = (line: string): string => - line.replace(/\$\$\{([^}]*)\}/g, (match, expr: string, at: number) => - COUNTER.test(expr) && PARAM_BEFORE.test(line.slice(Math.max(0, at - 16), at)) && PARAM_AFTER.test(line.slice(at + match.length)) && !inSqlQuote(line, at) ? '' : match) +export const withoutPlaceholders = (line: string): string => { + const token = /\\[\s\S]|\$\$\{([^}]{0,80})\}|[`'"]/g + let single = 0 + let double = 0 + let out = '' + let kept = 0 -/** An odd count of `'` between the template literal's opening backtick and `at`: inside a quoted SQL string. */ -const inSqlQuote = (line: string, at: number): boolean => - (line.slice(line.lastIndexOf('`', at) + 1, at).match(/'/g) ?? []).length % 2 === 1 + for (let m = token.exec(line); m !== null; m = token.exec(line)) { + if (m[0][0] === '\\') continue + if (m[0] === '`') { single = 0; double = 0; continue } + if (m[0] === "'") { single++; continue } + if (m[0] === '"') { double++; continue } + const end = m.index + m[0].length + const isParam = single % 2 === 0 && double % 2 === 0 && COUNTER.test(m[1]) + && PARAM_BEFORE.test(line.slice(Math.max(0, m.index - 16), m.index)) && PARAM_AFTER.test(line.slice(end, end + 2)) + if (isParam) { out += line.slice(kept, m.index); kept = end } + } + + return out + line.slice(kept) +} /** The old `/\$\{.*\}.*sql|sql.*\$\{/i`, in linear time: a long minified line made the regex quadratic. */ const sqlInterpolation = (line: string): boolean => { @@ -74,65 +70,96 @@ export const CODE_PATTERNS: readonly CodePattern[] = [ { match: re(/(? sqlInterpolation(line) && sqlInterpolation(withoutPlaceholders(line)), type: 'SQL Injection', severity: 'high', desc: 'Possible SQL injection' }, ] /** * The file's lines with comment text blanked (line count kept, so locations stay right). Strings are respected, so * `'http://x'` is not a comment; a template literal may span lines. Regex literals and JSX text are not parsed, so a - * `//` or `/*` inside one is taken as a comment. That can only hide the rest of that one line: a block comment carries - * to the next lines only when its `/*` starts the line, which a regex or JSX text never does. + * `//`, `/*` or backtick inside one can be misread. The damage is bounded to one line: a block comment carries to the + * next line only from a `/*` that starts its line, and only through lines that look like comment lines (they start + * with `*` or contain the closing `*` + `/`). Any other line ends the carried comment and is scanned as code. One pass, + * linear in the file size. */ export function codeLinesOf(content: string): string[] { const out: string[] = [] let inBlock = false let inTemplate = false - let offset = 0 - for (const line of content.split('\n')) { - let code = '' + if (inBlock && !/^\s*\*|\*\//.test(line)) inBlock = false + const parts: string[] = [] + let tail = '' + let hasCode = false let quote: string | null = inTemplate ? '`' : null let carries = inBlock + // Parts plus a 12-character tail, not one growing string: slicing a concatenated string flattens it each time. + const emit = (text: string) => { + parts.push(text) + tail = (tail + text).slice(-12) + if (/\S/.test(text)) hasCode = true + } for (let i = 0; i < line.length; i++) { const ch = line[i] const next = line[i + 1] if (inBlock) { - if (ch === '*' && next === '/') { inBlock = false; i++; code += ' ' } + if (ch === '*' && next === '/') { inBlock = false; i++; emit(' ') } continue } - if (ch === '\\') { code += ch + (next ?? ''); i++; continue } + if (ch === '\\') { emit(ch + (next ?? '')); i++; continue } if (quote !== null) { if (ch === quote) quote = null - code += ch + emit(ch) continue } - if (ch === '/' && next === '/') break + // `://` is a URL scheme, not a comment. + if (ch === '/' && next === '/' && line[i - 1] !== ':') break if (ch === '/' && next === '*') { inBlock = true - // Carried past this line only from a line-start opener that is closed later in the file: JSX text or a regex - // never starts a line with an unclosed comment, so neither can blank the lines after it. - carries = code.trim() === '' && content.indexOf('*/', offset + i + 2) >= 0 + carries = !hasCode i++ - code += ' ' + emit(' ') continue } + if (ch === '/' && REGEX_MAY_START.test(tail)) { + const end = regexEnd(line, i) + if (end > i) { emit(line.slice(i, end + 1)); i = end; continue } + } if (ch === '"' || ch === "'" || ch === '`') quote = ch - code += ch + emit(ch) } if (inBlock && !carries) inBlock = false inTemplate = quote === '`' - out.push(code) - offset += line.length + 1 + out.push(parts.join('')) } return out } +/** Code so far ends where an expression starts, so a `/` there opens a regex literal, not a division. */ +const REGEX_MAY_START = /(?:^|[(,=:[!&|?{};+\-*%<>~^]|\b(?:return|typeof|case|do|else|in|of|void|yield|await))\s*$/ + +/** + * The index of the `/` closing a regex literal that opens at `start`, or -1 when the line has none (then it was a + * division). Its text is kept as code, so misreading a regex can only keep comment text, never blank code. + */ +function regexEnd(line: string, start: number): number { + let inClass = false + // Bounded, so a line of `(/` cannot make the stripper quadratic; a longer regex is read as code, which is safe. + for (let i = start + 1; i < Math.min(line.length, start + 200); i++) { + const ch = line[i] + if (ch === '\\') { i++; continue } + if (ch === '[') inClass = true + else if (ch === ']') inClass = false + else if (ch === '/' && !inClass) return i + } + return -1 +} + /** * Generated report assets, named by what the report writes, inside a folder its marker file identifies. Only those * entries are skipped: other files in a folder that merely shares the name are still scanned.