All files / server/services process-executor.ts

69.04% Statements 58/84
49.18% Branches 30/61
80% Functions 8/10
70.73% Lines 58/82

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                                                                                      20x                                                                                   63x       63x 63x           63x 223x 223x 711x 223x 223x     223x                   107x 107x 107x                     63x   63x     63x   63x 63x 63x 63x   63x           63x     63x 63x         63x 1x 1x         63x 63x 63x 45x 45x     63x 63x 11x 11x           63x 63x                               63x 47x 46x 46x   47x   47x           47x     47x 11x 11x     47x     63x 2x 2x 2x   2x 2x 2x                                                                               2x      
/**
 * ProcessExecutor – Centralized, secure process spawning service
 * 
 * Provides unified process execution with:
 * - Command whitelisting (security)
 * - Argument validation (injection prevention)
 * - Timeout management (resource protection)
 * - Unified logging
 * - Test mockability
 */
 
import { ChildProcess } from "node:child_process";
import { Logger } from "@shared/logger";
import { config } from "../config";
 
/**
 * Extend globalThis for test process tracking
 * Note: spawnInstances is an implementation detail for test cleanup support
 */
declare global {
  interface Global {
    spawnInstances?: ChildProcess[];
  }
}
 
interface ExecutionOptions {
  timeout?: number;          // ms, 0 = no timeout
  detached?: boolean;        // process group for killing subprocesses
  stdio?: "pipe" | "ignore" | "inherit";
  onData?: (data: Buffer) => void;  // for stdout/stderr capture
  onProcess?: (proc: ChildProcess) => void;  // for process lifecycle hooks (tests)
}
 
interface ExecutionResult {
  code: number;
  stdout?: string;
  stderr?: string;
  error?: Error;
}
 
/**
 * Whitelist of allowed commands to prevent arbitrary execution
 */
const ALLOWED_COMMANDS: Record<string, { allowedArgs?: RegExp[] }> = {
  "docker": {
    // Docker command whitelist: allow specific flags and arguments
    allowedArgs: [
      /^--version$/,
      /^--no-color$/,
      /^info$/,
      /^image$/,
      /^inspect$/,
      /^run$/,
      /^pause$/,
      /^unpause$/,
      /^[a-z0-9:./-]+$/i, // Image names, paths, config values
    ],
  },
  "arduino-cli": {
    // Arduino CLI whitelisting
    allowedArgs: [
      /^compile$/,
      /^--fqbn$/,
      /^--build-path$/,
      /^arduino:avr:uno$/,
      /^[a-zA-Z0-9._\-/]+$/, // Paths and valid arg values
    ],
  },
  "g++": {
    // g++ is less restricted but still validated
    allowedArgs: [
      /^-[a-z]+$/i, // Flags like -o, -pthread
      /^[a-zA-Z0-9._\-/]+$/, // Paths and filenames
    ],
  },
  "echo": {
    // echo for testing - allow any args
  },
};
 
/**
 * Validate that command is in whitelist and arguments don't contain shell metacharacters
 */
function validateCommand(command: string, args: string[]): void {
  // Command must be in whitelist
  Iif (!ALLOWED_COMMANDS[command]) {
    throw new Error(`Command not whitelisted: ${command}`);
  }
 
  const allowedRegexps = ALLOWED_COMMANDS[command].allowedArgs;
  Iif (!allowedRegexps) {
    // No restriction for this command
    return;
  }
 
  // Check each argument against patterns
  for (const arg of args) {
    let isAllowed = false;
    for (const pattern of allowedRegexps) {
      if (pattern.test(arg)) {
        isAllowed = true;
        break;
      }
    }
    Iif (!isAllowed) {
      // Reject suspicious arguments
      if (/[;&|`$(){}]/.test(arg)) {
        throw new Error(`Argument contains shell metacharacters: ${arg}`);
      }
    }
  }
}
 
export class ProcessExecutor {
  private readonly logger = new Logger("ProcessExecutor");
  private activeProcess: ChildProcess | null = null;
  private activeTimeout: NodeJS.Timeout | null = null;
 
  /**
   * Execute a process with strict validation and timeout management
   */
  async execute(
    command: string,
    args: string[],
    options: ExecutionOptions = {},
  ): Promise<ExecutionResult> {
    // Validate command and arguments
    validateCommand(command, args);
 
    const { timeout = config.timeouts.processExecutionDefaultMs, detached = false, stdio = "pipe", onData, onProcess } = options;
 
    // Dynamic import for test mockability
    const { spawn } = await import("node:child_process");
 
    return new Promise((resolve) => {
      let stdout = "";
      let stderr = "";
      let timedOut = false;
 
      const proc = spawn(command, args, {
        stdio: [stdio === "pipe" ? "ignore" : stdio, stdio, stdio],
        detached,
        shell: false, // Critical security: never use shell
      });
 
      this.activeProcess = proc;
 
      // Track in global spawnInstances for test cleanup (Vitest pattern)
      const spawnInstances = (globalThis as any).spawnInstances as ChildProcess[] | undefined;
      Iif (spawnInstances && Array.isArray(spawnInstances)) {
        spawnInstances.push(proc);
      }
 
      // Allow caller to instrument the process (test mocks)
      if (onProcess) {
        try {
          onProcess(proc);
        } catch {}
      }
 
      // Capture output
      Eif (stdio === "pipe") {
        Eif (proc.stdout) {
          proc.stdout.on("data", (data: Buffer) => {
            stdout += data.toString();
            Iif (onData) onData(data);
          });
        }
        Eif (proc.stderr) {
          proc.stderr.on("data", (data: Buffer) => {
            stderr += data.toString();
            Iif (onData) onData(data);
          });
        }
      }
 
      // Set timeout if requested
      Eif (timeout > 0) {
        this.activeTimeout = setTimeout(() => {
          timedOut = true;
          try {
            // Kill process group if detached, otherwise just the process
            if (detached && proc.pid) {
              process.kill(-proc.pid, "SIGKILL");
            } else {
              proc.kill("SIGKILL");
            }
          } catch (err) {
            this.logger.warn(`Failed to kill process: ${err}`);
          }
        }, timeout);
      }
 
      // Handle process completion
      proc.on("close", (code: number) => {
        if (this.activeTimeout) {
          clearTimeout(this.activeTimeout);
          this.activeTimeout = null;
        }
        this.activeProcess = null;
 
        const result: ExecutionResult = {
          code,
          stdout: stdio === "pipe" ? stdout : undefined,
          stderr: stdio === "pipe" ? stderr : undefined,
        };
 
        Iif (timedOut) {
          result.error = new Error(`Process timeout after ${timeout}ms`);
          this.logger.warn(`${command} timed out: ${result.error.message}`);
        } else if (code !== 0) {
          result.error = new Error(`${command} exit code ${code}: ${stderr}`);
          this.logger.warn(`${command} failed: ${result.error.message}`);
        }
 
        resolve(result);
      });
 
      proc.on("error", (err: Error) => {
        Eif (this.activeTimeout) {
          clearTimeout(this.activeTimeout);
          this.activeTimeout = null;
        }
        this.activeProcess = null;
        this.logger.error(`${command} error: ${err.message}`);
        resolve({
          code: -1,
          error: err,
          stdout: stdio === "pipe" ? stdout : undefined,
          stderr: stdio === "pipe" ? stderr : undefined,
        });
      });
    });
  }
 
  /**
   * Kill any active process (for cleanup during stop())
   */
  kill(signal: string | number = "SIGKILL"): void {
    if (this.activeProcess?.pid) {
      try {
        // Check if this is a detached process (has own process group)
        const isDetached = (this.activeProcess as any)._isDetached;
        if (isDetached) {
          // Kill process group
          process.kill(-this.activeProcess.pid, signal as any);
        } else {
          this.activeProcess.kill(signal as any);
        }
        this.logger.info(`Killed process with signal ${signal}`);
      } catch (err) {
        this.logger.warn(`Failed to kill process: ${err}`);
      }
    }
 
    if (this.activeTimeout) {
      clearTimeout(this.activeTimeout);
      this.activeTimeout = null;
    }
  }
 
  /**
   * Check if a process is currently running
   */
  get isBusy(): boolean {
    return this.activeProcess !== null;
  }
}