All files / src safe-executor.ts

0% Statements 0/525
0% Branches 0/1
0% Functions 0/1
0% Lines 0/525

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
/**
 * 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',
      'npx',
      'node',
      'tsc',
      'vitest',
      'eslint',
      'prettier',
    ],
  });
}

/**
 * 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,
  });
}