Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix(security): keep the old command-injection reach; bound the comment stripper

Dragan Spiridonov58604dabcee0
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({
+ '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(['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 = <kbd>`</kbd>;\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({
- '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']);",
+ '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([1, 2, 3, 5, 6, 7, 8].map(n => `Command Injection m.ts:${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
+
+ 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 }
+ }
-/** 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
+ 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(/(?<![\w$])eval\s*\(/), type: 'Eval Usage', severity: 'medium', desc: 'eval() can execute arbitrary code' },
{ match: re(/innerHTML\s*=/), type: 'innerHTML', severity: 'medium', desc: 'XSS risk with innerHTML' },
{ match: re(/dangerouslySetInnerHTML/), type: 'React XSS', severity: 'medium', desc: 'React XSS risk' },
- { match: commandInjection, type: 'Command Injection', severity: 'high', desc: 'Possible command injection' },
+ { match: re(/child_process.*exec/), type: 'Command Injection', severity: 'high', desc: 'Possible command injection' },
{ match: line => 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.