All files / server/services docker-command-builder.ts

100% Statements 2/2
100% Branches 0/0
100% Functions 2/2
100% Lines 2/2

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                                                4x                                                         4x              
/**
 * Docker Command Builder
 * 
 * Handles the construction of secure Docker run commands with all necessary
 * security constraints and resource limits for Arduino sketch execution.
 */
 
export interface DockerRunOptions {
  sketchDir: string;
  memoryMB: number;
  cpuLimit: string;
  pidsLimit: number;
  imageName: string;
  command: string[];
}
 
export class DockerCommandBuilder {
  /**
   * Builds a secure Docker run command with all security constraints
   * 
   * @param options - Docker run configuration
   * @returns Array of command arguments for spawn
   */
  static buildSecureRunCommand(options: DockerRunOptions): string[] {
    return [
      "run",
      "--rm", // Remove container after exit
      "-i", // Interactive mode for stdin
      "--network",
      "none", // No network access
      "--memory",
      `${options.memoryMB}m`, // Memory limit
      "--memory-swap",
      `${options.memoryMB}m`, // Disable swap
      "--cpus",
      options.cpuLimit, // CPU limit (e.g., "0.5" for 50%)
      "--pids-limit",
      String(options.pidsLimit), // Limit number of processes
      "--security-opt",
      "no-new-privileges", // Prevent privilege escalation
      "--cap-drop",
      "ALL", // Drop all Linux capabilities
      "-v",
      `${options.sketchDir}:/sandbox:rw`, // Mount sketch directory
      options.imageName,
      ...options.command, // Execution command
    ];
  }
 
  /**
   * Builds the compile and run command for Docker
   */
  static buildCompileAndRunCommand(): string[] {
    return [
      "sh",
      "-c",
      "g++ /sandbox/sketch.cpp -o /tmp/sketch -pthread 2>&1 && /tmp/sketch",
    ];
  }
}