mirror of
https://github.com/ruvnet/ruflo.git
synced 2026-11-24 22:28:10 +09:00
* fix: critical security & performance fixes across 6 packages Addresses 11 vulnerabilities from security audit + 5 additional issues found during devil's advocate review, plus test suite fixes across memory, security, and swarm packages. ## Security Fixes (Critical) - CRIT-01: SQL injection in embeddings search — replaced string interpolation with parameterized queries (db.prepare/bind) - CRIT-02: Command injection in 4 files — replaced execSync template literals with execFileSync + input validation regex: - ruvector/import.ts (docker container name) - init.ts (embedding model name, 2 locations) - agent-browser-adapter.ts (CLI args) - CRIT-03: Browser eval hardening — 12 dangerous patterns blocked, configurable 20KB length limit via CLAUDE_FLOW_MAX_EVAL_SCRIPT_LENGTH ## Security Fixes (High) - HIGH-01: ESLint rules restricting child_process imports (both import and require) with overrides for safe-executor/daemon/mcp-server - HIGH-02: Hive-mind truthiness fix (=== true vs !== false) - HIGH-03: Prototype pollution prevention — safeJsonParse with JSON reviver stripping __proto__/constructor/prototype in 3 memory backends - HIGH-04: Plugin sandbox warning on unsandboxed plugin load - HIGH-05: HNSW hash collision fix — dual-hash (djb2+sdbm) producing 53-bit values with bidirectional map and linear probing ## Security Fixes (DA Review) - DA-CRIT-1: Local json-security.ts to avoid cross-package imports - DA-CRIT-2: PostgreSQL schema name validation (validateSchemaName) added to all 6 ruvector commands via pg-utils.ts - DA-CRIT-3: PID injection prevention in mcp-server — /proc read + execFileSync replacing execSync with PID interpolation - DA-HIGH-3: Timestamp validation (validateTimestamp) in ruvector import - DA-HIGH-4: 4 additional browser eval bypass patterns (globalThis, .constructor, Reflect, eval()) - DA-HIGH-5: ESLint no-restricted-modules for require() coverage ## Performance Fixes - PERF-01: BoundedSet<T> for gossip seenMessages — Map-based LRU eviction capped at 100K entries, prevents unbounded memory growth - PERF-02: Bulk operations use Promise.allSettled with batch size 50, logging partial failures instead of aborting - PERF-03: CLI lazy loading — reduced sync imports from 37 to 10 core commands, async getCommandsByCategory() for help display ## Test Suite Fixes - Fixed 11 broken import paths in security tests (../../security/ → ../src/ and ../../helpers/ → ../helpers/) - Added vitest.config.ts for security package (was inheriting root config with missing setup.ts reference) - Added allowedDirectories to SecurityConfig test fixture - Fixed sanitizePath test expectation (leading slash removal) - Fixed hardcoded /workspaces/claude-flow path in memory tests - Fixed semanticRouter controller test (auto-enables with agentdb) - Fixed database-provider count test (namespace-scoped assertion) - Fixed swarm latency tests (toBeGreaterThanOrEqual for sub-ms mocks) - Added TypeScript as dev dependency for build verification ## Verification - 22 automated security verification tests in security-verification.test.ts covering all 10 user-facing scenarios - All 5 packages type-check clean (0 errors) - memory: 9/9 suites, 353/353 tests pass - swarm: 4/4 suites, 172/172 tests pass - security: 13/13 suites, 444/444 tests pass - CLI help displays all 35 commands correctly with lazy loading ## New Files - v3/@claude-flow/cli/src/commands/ruvector/pg-utils.ts - v3/@claude-flow/cli/.eslintrc.json - v3/@claude-flow/cli/__tests__/security-verification.test.ts - v3/@claude-flow/memory/src/json-security.ts - v3/@claude-flow/security/vitest.config.ts Co-Authored-By: claude-flow <ruv@ruv.net> * fix: address Sherlock review findings for PR #1558 Finding 2 (MUST FIX): Add formatEmbedding array-element validation - Validate each embedding value is typeof number && Number.isFinite() - Prevents SQL injection via crafted JSON arrays with string payloads - Throws descriptive error with index for debugging Finding 1: Reclassify CRIT-03 eval blocklist as defense-in-depth - Add comment clarifying pattern blocklist is best-effort, not a sandbox - Primary defense is the browser sandbox itself - Update test description to reflect defense-in-depth classification Finding 3: Add behavioral tests alongside source-guards - Add formatEmbedding behavioral test with hostile inputs (NaN, Infinity, strings) - Add CRIT-02 behavioral test verifying execFileSync array argument pattern - Categorize existing tests as source-guard vs behavioral in comments Finding 4: Flag HIGH-02 as behavior change - Add comment explaining === true vs !== false semantic difference - Documents that undefined/null no longer treated as "skip permissions" Finding 6: Export BoundedSet, fix test semantics - Export BoundedSet from gossip.ts for reuse - Fix test to use FIFO semantics matching production (not LRU) - Add FIFO-specific test: re-adding doesn't refresh position Finding 7: Fix BoundedSet comment math - Remove speculative throughput time estimate - Use factual memory calculation: 100K × ~40B IDs ≈ 4MB Finding 5: No change (false positive — Math.abs in manhattanDistance is correct) Co-Authored-By: claude-flow <ruv@ruv.net> --------- Co-authored-by: claude-flow <ruv@ruv.net>
547 lines
12 KiB
TypeScript
547 lines
12 KiB
TypeScript
/**
|
|
* Safe Executor - HIGH-1 Remediation
|
|
*
|
|
* Fixes command injection vulnerabilities by:
|
|
* - Using execFile instead of exec with shell
|
|
* - Validating all command arguments
|
|
* - Implementing command allowlist
|
|
* - Sanitizing command inputs
|
|
*
|
|
* Security Properties:
|
|
* - No shell interpretation
|
|
* - Argument validation
|
|
* - Command allowlist enforcement
|
|
* - Timeout controls
|
|
* - Resource limits
|
|
*
|
|
* @module v3/security/safe-executor
|
|
*/
|
|
|
|
import { execFile, spawn, ChildProcess } from 'child_process';
|
|
import { promisify } from 'util';
|
|
import * as path from 'path';
|
|
|
|
const execFileAsync = promisify(execFile);
|
|
|
|
export interface ExecutorConfig {
|
|
/**
|
|
* Allowed commands (allowlist).
|
|
* Only commands in this list can be executed.
|
|
*/
|
|
allowedCommands: string[];
|
|
|
|
/**
|
|
* Blocked argument patterns (regex strings).
|
|
* Arguments matching these patterns are rejected.
|
|
*/
|
|
blockedPatterns?: string[];
|
|
|
|
/**
|
|
* Maximum execution timeout in milliseconds.
|
|
* Default: 30000 (30 seconds)
|
|
*/
|
|
timeout?: number;
|
|
|
|
/**
|
|
* Maximum buffer size for stdout/stderr.
|
|
* Default: 10MB
|
|
*/
|
|
maxBuffer?: number;
|
|
|
|
/**
|
|
* Working directory for command execution.
|
|
* Default: process.cwd()
|
|
*/
|
|
cwd?: string;
|
|
|
|
/**
|
|
* Environment variables to include.
|
|
* Default: process.env
|
|
*/
|
|
env?: NodeJS.ProcessEnv;
|
|
|
|
/**
|
|
* Whether to allow sudo commands.
|
|
* Default: false
|
|
*/
|
|
allowSudo?: boolean;
|
|
}
|
|
|
|
export interface ExecutionResult {
|
|
stdout: string;
|
|
stderr: string;
|
|
exitCode: number;
|
|
command: string;
|
|
args: string[];
|
|
duration: number;
|
|
}
|
|
|
|
export interface StreamingExecutor {
|
|
process: ChildProcess;
|
|
stdout: NodeJS.ReadableStream | null;
|
|
stderr: NodeJS.ReadableStream | null;
|
|
promise: Promise<ExecutionResult>;
|
|
}
|
|
|
|
export class SafeExecutorError extends Error {
|
|
constructor(
|
|
message: string,
|
|
public readonly code: string,
|
|
public readonly command?: string,
|
|
public readonly args?: string[],
|
|
) {
|
|
super(message);
|
|
this.name = 'SafeExecutorError';
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Default blocked argument patterns.
|
|
* These patterns indicate potential command injection attempts.
|
|
*/
|
|
const DEFAULT_BLOCKED_PATTERNS = [
|
|
// Shell metacharacters
|
|
';',
|
|
'&&',
|
|
'||',
|
|
'|',
|
|
'`',
|
|
'$(',
|
|
'${',
|
|
// Redirection
|
|
'>',
|
|
'<',
|
|
'>>',
|
|
// Background execution
|
|
'&',
|
|
// Newlines (command chaining)
|
|
'\n',
|
|
'\r',
|
|
// Null byte injection
|
|
'\0',
|
|
// Command substitution
|
|
'$()',
|
|
];
|
|
|
|
/**
|
|
* Commands that are inherently dangerous and should never be allowed.
|
|
*/
|
|
const DANGEROUS_COMMANDS = [
|
|
'rm',
|
|
'rmdir',
|
|
'del',
|
|
'format',
|
|
'mkfs',
|
|
'dd',
|
|
'chmod',
|
|
'chown',
|
|
'kill',
|
|
'killall',
|
|
'pkill',
|
|
'reboot',
|
|
'shutdown',
|
|
'init',
|
|
'poweroff',
|
|
'halt',
|
|
];
|
|
|
|
/**
|
|
* Safe command executor that prevents command injection.
|
|
*
|
|
* This class replaces unsafe exec() and spawn({shell: true}) calls
|
|
* with validated execFile() calls.
|
|
*
|
|
* @example
|
|
* ```typescript
|
|
* const executor = new SafeExecutor({
|
|
* allowedCommands: ['git', 'npm', 'node']
|
|
* });
|
|
*
|
|
* const result = await executor.execute('git', ['status']);
|
|
* ```
|
|
*/
|
|
export class SafeExecutor {
|
|
private readonly config: Required<ExecutorConfig>;
|
|
private readonly blockedPatterns: RegExp[];
|
|
|
|
constructor(config: ExecutorConfig) {
|
|
this.config = {
|
|
allowedCommands: config.allowedCommands,
|
|
blockedPatterns: config.blockedPatterns ?? DEFAULT_BLOCKED_PATTERNS,
|
|
timeout: config.timeout ?? 30000,
|
|
maxBuffer: config.maxBuffer ?? 10 * 1024 * 1024, // 10MB
|
|
cwd: config.cwd ?? process.cwd(),
|
|
env: config.env ?? process.env,
|
|
allowSudo: config.allowSudo ?? false,
|
|
};
|
|
|
|
// Compile blocked patterns for performance
|
|
this.blockedPatterns = this.config.blockedPatterns.map(
|
|
pattern => new RegExp(this.escapeRegExp(pattern), 'i')
|
|
);
|
|
|
|
this.validateConfig();
|
|
}
|
|
|
|
/**
|
|
* Escapes special regex characters.
|
|
*/
|
|
private escapeRegExp(str: string): string {
|
|
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
}
|
|
|
|
/**
|
|
* Validates executor configuration.
|
|
*/
|
|
private validateConfig(): void {
|
|
if (this.config.allowedCommands.length === 0) {
|
|
throw new SafeExecutorError(
|
|
'At least one allowed command must be specified',
|
|
'EMPTY_ALLOWLIST'
|
|
);
|
|
}
|
|
|
|
// Check for dangerous commands in allowlist
|
|
const dangerousAllowed = this.config.allowedCommands.filter(
|
|
cmd => DANGEROUS_COMMANDS.includes(path.basename(cmd))
|
|
);
|
|
|
|
if (dangerousAllowed.length > 0) {
|
|
throw new SafeExecutorError(
|
|
`Dangerous commands cannot be allowed: ${dangerousAllowed.join(', ')}`,
|
|
'DANGEROUS_COMMAND_ALLOWED'
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Validates a command against the allowlist.
|
|
*
|
|
* @param command - Command to validate
|
|
* @throws SafeExecutorError if command is not allowed
|
|
*/
|
|
private validateCommand(command: string): void {
|
|
const basename = path.basename(command);
|
|
|
|
// Check if command is allowed
|
|
const isAllowed = this.config.allowedCommands.some(allowed => {
|
|
const allowedBasename = path.basename(allowed);
|
|
return command === allowed || basename === allowedBasename;
|
|
});
|
|
|
|
if (!isAllowed) {
|
|
throw new SafeExecutorError(
|
|
`Command not in allowlist: ${command}`,
|
|
'COMMAND_NOT_ALLOWED',
|
|
command
|
|
);
|
|
}
|
|
|
|
// Check for sudo
|
|
if (!this.config.allowSudo && (command === 'sudo' || basename === 'sudo')) {
|
|
throw new SafeExecutorError(
|
|
'Sudo commands are not allowed',
|
|
'SUDO_NOT_ALLOWED',
|
|
command
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Validates command arguments for injection patterns.
|
|
*
|
|
* @param args - Arguments to validate
|
|
* @throws SafeExecutorError if arguments contain dangerous patterns
|
|
*/
|
|
private validateArguments(args: string[]): void {
|
|
for (const arg of args) {
|
|
// Check for null bytes
|
|
if (arg.includes('\0')) {
|
|
throw new SafeExecutorError(
|
|
'Null byte detected in argument',
|
|
'NULL_BYTE_INJECTION',
|
|
undefined,
|
|
args
|
|
);
|
|
}
|
|
|
|
// Check against blocked patterns
|
|
for (const pattern of this.blockedPatterns) {
|
|
if (pattern.test(arg)) {
|
|
throw new SafeExecutorError(
|
|
`Dangerous pattern detected in argument: ${arg}`,
|
|
'DANGEROUS_PATTERN',
|
|
undefined,
|
|
args
|
|
);
|
|
}
|
|
}
|
|
|
|
// Check for command chaining attempts
|
|
if (/^-.*[;&|]/.test(arg)) {
|
|
throw new SafeExecutorError(
|
|
`Potential command chaining in argument: ${arg}`,
|
|
'COMMAND_CHAINING',
|
|
undefined,
|
|
args
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Sanitizes a single argument.
|
|
*
|
|
* @param arg - Argument to sanitize
|
|
* @returns Sanitized argument
|
|
*/
|
|
sanitizeArgument(arg: string): string {
|
|
// Remove null bytes
|
|
let sanitized = arg.replace(/\0/g, '');
|
|
|
|
// Remove shell metacharacters
|
|
sanitized = sanitized.replace(/[;&|`$(){}><\n\r]/g, '');
|
|
|
|
return sanitized;
|
|
}
|
|
|
|
/**
|
|
* Executes a command safely.
|
|
*
|
|
* @param command - Command to execute (must be in allowlist)
|
|
* @param args - Command arguments
|
|
* @returns Execution result
|
|
* @throws SafeExecutorError on validation failure or execution error
|
|
*/
|
|
async execute(command: string, args: string[] = []): Promise<ExecutionResult> {
|
|
const startTime = Date.now();
|
|
|
|
// Validate command
|
|
this.validateCommand(command);
|
|
|
|
// Validate arguments
|
|
this.validateArguments(args);
|
|
|
|
try {
|
|
// Execute command WITHOUT shell
|
|
const { stdout, stderr } = await execFileAsync(command, args, {
|
|
cwd: this.config.cwd,
|
|
env: this.config.env,
|
|
timeout: this.config.timeout,
|
|
maxBuffer: this.config.maxBuffer,
|
|
shell: false, // CRITICAL: Never use shell
|
|
windowsHide: true,
|
|
});
|
|
|
|
return {
|
|
stdout: stdout.toString(),
|
|
stderr: stderr.toString(),
|
|
exitCode: 0,
|
|
command,
|
|
args,
|
|
duration: Date.now() - startTime,
|
|
};
|
|
} catch (error: any) {
|
|
// Handle execution errors
|
|
if (error.killed) {
|
|
throw new SafeExecutorError(
|
|
'Command execution timed out',
|
|
'TIMEOUT',
|
|
command,
|
|
args
|
|
);
|
|
}
|
|
|
|
if (error.code === 'ENOENT') {
|
|
throw new SafeExecutorError(
|
|
`Command not found: ${command}`,
|
|
'COMMAND_NOT_FOUND',
|
|
command,
|
|
args
|
|
);
|
|
}
|
|
|
|
// Return result with non-zero exit code
|
|
return {
|
|
stdout: error.stdout?.toString() ?? '',
|
|
stderr: error.stderr?.toString() ?? error.message,
|
|
exitCode: error.code ?? 1,
|
|
command,
|
|
args,
|
|
duration: Date.now() - startTime,
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Executes a command with streaming output.
|
|
*
|
|
* @param command - Command to execute
|
|
* @param args - Command arguments
|
|
* @returns Streaming executor with process handles
|
|
*/
|
|
executeStreaming(command: string, args: string[] = []): StreamingExecutor {
|
|
const startTime = Date.now();
|
|
|
|
// Validate command
|
|
this.validateCommand(command);
|
|
|
|
// Validate arguments
|
|
this.validateArguments(args);
|
|
|
|
// Spawn process WITHOUT shell
|
|
const childProcess = spawn(command, args, {
|
|
cwd: this.config.cwd,
|
|
env: this.config.env,
|
|
timeout: this.config.timeout,
|
|
shell: false, // CRITICAL: Never use shell
|
|
windowsHide: true,
|
|
});
|
|
|
|
const promise = new Promise<ExecutionResult>((resolve, reject) => {
|
|
let stdout = '';
|
|
let stderr = '';
|
|
|
|
childProcess.stdout?.on('data', (data: Buffer) => {
|
|
stdout += data.toString();
|
|
});
|
|
|
|
childProcess.stderr?.on('data', (data: Buffer) => {
|
|
stderr += data.toString();
|
|
});
|
|
|
|
childProcess.on('close', (code) => {
|
|
resolve({
|
|
stdout,
|
|
stderr,
|
|
exitCode: code ?? 0,
|
|
command,
|
|
args,
|
|
duration: Date.now() - startTime,
|
|
});
|
|
});
|
|
|
|
childProcess.on('error', (error) => {
|
|
reject(new SafeExecutorError(
|
|
error.message,
|
|
'EXECUTION_ERROR',
|
|
command,
|
|
args
|
|
));
|
|
});
|
|
});
|
|
|
|
return {
|
|
process: childProcess,
|
|
stdout: childProcess.stdout,
|
|
stderr: childProcess.stderr,
|
|
promise,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Adds a command to the allowlist at runtime.
|
|
*
|
|
* @param command - Command to add
|
|
*/
|
|
allowCommand(command: string): void {
|
|
const basename = path.basename(command);
|
|
|
|
if (DANGEROUS_COMMANDS.includes(basename)) {
|
|
throw new SafeExecutorError(
|
|
`Cannot allow dangerous command: ${command}`,
|
|
'DANGEROUS_COMMAND'
|
|
);
|
|
}
|
|
|
|
if (!this.config.allowedCommands.includes(command)) {
|
|
this.config.allowedCommands.push(command);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Checks if a command is allowed.
|
|
*
|
|
* @param command - Command to check
|
|
* @returns True if command is allowed
|
|
*/
|
|
isCommandAllowed(command: string): boolean {
|
|
const basename = path.basename(command);
|
|
return this.config.allowedCommands.some(allowed => {
|
|
const allowedBasename = path.basename(allowed);
|
|
return command === allowed || basename === allowedBasename;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Returns the current allowlist.
|
|
*/
|
|
getAllowedCommands(): readonly string[] {
|
|
return [...this.config.allowedCommands];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Factory function to create a safe executor for common development tasks.
|
|
*
|
|
* @returns Configured SafeExecutor for git, npm, and node
|
|
*/
|
|
export function createDevelopmentExecutor(): SafeExecutor {
|
|
return new SafeExecutor({
|
|
allowedCommands: [
|
|
'git',
|
|
'npm',
|
|
'node',
|
|
'tsc',
|
|
'vitest',
|
|
'eslint',
|
|
'prettier',
|
|
],
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Factory function to create a CLI executor.
|
|
* Allows commands commonly needed by CLI command handlers.
|
|
*
|
|
* @returns Configured SafeExecutor for CLI operations
|
|
*/
|
|
export function createCliExecutor(): SafeExecutor {
|
|
return new SafeExecutor({
|
|
allowedCommands: [
|
|
'git',
|
|
'npm',
|
|
'npx',
|
|
'node',
|
|
'docker',
|
|
'which',
|
|
'tsc',
|
|
'vitest',
|
|
],
|
|
timeout: 60000,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Factory function to create a read-only executor.
|
|
* Only allows commands that read without modifying.
|
|
*
|
|
* @returns Configured SafeExecutor for read operations
|
|
*/
|
|
export function createReadOnlyExecutor(): SafeExecutor {
|
|
return new SafeExecutor({
|
|
allowedCommands: [
|
|
'git',
|
|
'cat',
|
|
'head',
|
|
'tail',
|
|
'ls',
|
|
'find',
|
|
'grep',
|
|
'which',
|
|
'echo',
|
|
],
|
|
timeout: 10000,
|
|
});
|
|
}
|