All files / agent/src docker.ts

86.69% Statements 378/436
62.79% Branches 27/43
86.66% Functions 13/15
86.69% Lines 378/436

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 4361x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 1x 1x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 2x 2x 2x 2x 2x 6x 6x 6x 2x 2x 6x 6x 6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x                       6x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x     3x 3x 3x 3x 3x 3x 3x       3x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 3x 1x 1x 1x 3x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x       7x 7x 7x 7x       7x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x       6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 5x 5x 15x 15x 15x 15x 15x 15x 15x 15x 1x 1x 1x 1x 1x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x 1x 1x 1x 1x 1x 30x 30x 30x 28x 28x 28x 28x 1x 1x 30x 30x 30x 30x             30x 30x 30x 30x 30x 1x 1x 30x 30x 30x 30x 30x 30x 30x 30x 30x 30x           30x 30x 30x 1x
/**
 * Docker Manager - Container management for job execution
 * 
 * Handles Docker container lifecycle, security configuration,
 * and resource management for isolated job execution.
 * 
 * Enhanced with comprehensive security measures and monitoring.
 * 
 * Requirements: 4.1, 4.2, 4.3, 4.4, 4.5
 */
 
import { DockerConfig } from './config/types.js';
import { createLogger } from './utils/logger.js';
import { SecurityManager, SecurityConfig, SecurityViolation } from './security.js';
import { spawn, ChildProcess } from 'child_process';
import { promises as fs } from 'fs';
import { join } from 'path';
 
const logger = createLogger('docker');
 
export interface ContainerConfig {
  image: string;
  workDir: string;
  environment: Record<string, string>;
  volumeMounts: Array<{
    hostPath: string;
    containerPath: string;
    readOnly: boolean;
  }>;
}
 
export interface ExecutionOptions {
  timeout?: number;
  onOutput?: (output: string) => void;
}
 
export interface ExecutionResult {
  exitCode: number;
  output: string;
  error?: string;
}
 
export class DockerManager {
  private config: DockerConfig;
  private securityManager: SecurityManager;
  private activeContainers = new Set<string>();
  private containerTempDirs = new Map<string, string>();
 
  constructor(config: DockerConfig, securityConfig: SecurityConfig) {
    this.config = config;
    this.securityManager = new SecurityManager(securityConfig);
    logger.info('Docker manager initialized with enhanced security');
  }
 
  /**
   * Check if Docker is available and running
   */
  async checkDockerAvailability(): Promise<boolean> {
    try {
      const result = await this.executeDockerCommand(['version', '--format', 'json']);
      return result.exitCode === 0;
    } catch (error) {
      logger.error('Docker is not available:', error);
      return false;
    }
  }
 
  /**
   * Pull Docker image
   */
  async pullImage(image: string): Promise<void> {
    logger.info(`Pulling Docker image: ${image}`);
    
    try {
      const result = await this.executeDockerCommand(['pull', image]);
      
      if (result.exitCode !== 0) {
        throw new Error(`Failed to pull image ${image}: ${result.error}`);
      }
      
      logger.info(`Successfully pulled image: ${image}`);
      
    } catch (error) {
      logger.error(`Failed to pull image ${image}:`, error);
      throw error;
    }
  }
 
  /**
   * Create a Docker container with enhanced security configuration
   */
  async createContainer(containerConfig: ContainerConfig): Promise<string> {
    const containerId = `buildhive-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
    
    logger.info(`Creating secure container: ${containerId}`);
 
    try {
      // Validate image security first
      const imageViolations = await this.securityManager.validateImageSecurity(containerConfig.image);
      if (imageViolations.some(v => v.severity === 'critical')) {
        throw new Error(`Image ${containerConfig.image} failed security validation`);
      }
 
      // Validate container configuration
      const configViolations = await this.securityManager.validateContainerConfig({
        ...containerConfig,
        containerId,
        memoryLimit: this.config.memoryLimit,
        cpuLimit: this.config.cpuLimit,
        networkMode: this.config.networkMode
      });
 
      if (configViolations.some(v => v.severity === 'critical')) {
        throw new Error(`Container configuration failed security validation`);
      }
 
      // Create secure temporary directory
      const tempDir = await this.securityManager.createSecureTempDir(containerId);
      this.containerTempDirs.set(containerId, tempDir);
 
      const dockerArgs = [
        'create',
        '--name', containerId,
        // No --rm: we handle cleanup explicitly via stopContainer/removeContainer
      ];
 
      // Add enhanced security arguments
      const securityArgs = this.securityManager.generateSecureDockerArgs(containerId);
      dockerArgs.push(...securityArgs);
 
      // Add basic configuration
      dockerArgs.push('--workdir', containerConfig.workDir);
 
      // Add volume mounts with security validation
      for (const mount of containerConfig.volumeMounts) {
        // Use secure temp directory for writable mounts
        const hostPath = mount.readOnly ? mount.hostPath : tempDir;
        const mountStr = `${hostPath}:${mount.containerPath}${mount.readOnly ? ':ro' : ''}`;
        dockerArgs.push('--volume', mountStr);
      }
 
      // Add environment variables
      for (const [key, value] of Object.entries(containerConfig.environment)) {
        dockerArgs.push('--env', `${key}=${value}`);
      }
 
      // Add the image and a keep-alive command so the container stays running
      dockerArgs.push(containerConfig.image);
      dockerArgs.push('tail', '-f', '/dev/null');
 
      // Execute docker create command
      const result = await this.executeDockerCommand(dockerArgs);
      
      if (result.exitCode !== 0) {
        throw new Error(`Failed to create container: ${result.error}`);
      }
 
      this.activeContainers.add(containerId);
      logger.info(`Secure container created successfully: ${containerId}`);
      
      return containerId;
      
    } catch (error) {
      logger.error(`Failed to create secure container ${containerId}:`, error);
      
      // Cleanup temp directory on failure
      const tempDir = this.containerTempDirs.get(containerId);
      if (tempDir) {
        await this.securityManager.cleanupSecureTempDir(tempDir);
        this.containerTempDirs.delete(containerId);
      }
      
      throw error;
    }
  }
 
  /**
   * Start a Docker container with security monitoring
   */
  async startContainer(containerId: string): Promise<void> {
    logger.info(`Starting secure container: ${containerId}`);
    
    try {
      const result = await this.executeDockerCommand(['start', containerId]);
      
      if (result.exitCode !== 0) {
        throw new Error(`Failed to start container ${containerId}: ${result.error}`);
      }
      
      // Start security monitoring
      await this.securityManager.startResourceMonitoring(containerId);
      
      logger.info(`Secure container started successfully: ${containerId}`);
      
    } catch (error) {
      logger.error(`Failed to start secure container ${containerId}:`, error);
      throw error;
    }
  }
 
  /**
   * Execute a command in a running container
   */
  async executeCommand(
    containerId: string,
    command: string,
    options: ExecutionOptions = {}
  ): Promise<ExecutionResult> {
    logger.info(`Executing command in container ${containerId}: ${command}`);
    
    try {
      const dockerArgs = [
        'exec',
        '--interactive',
        containerId,
        'sh', '-c', command
      ];
 
      const result = await this.executeDockerCommand(dockerArgs, {
        timeout: options.timeout,
        onOutput: options.onOutput
      });
 
      logger.info(`Command execution completed in container ${containerId} (exit code: ${result.exitCode})`);
      
      return result;
      
    } catch (error) {
      logger.error(`Failed to execute command in container ${containerId}:`, error);
      throw error;
    }
  }
 
  /**
   * Stop a running container
   */
  async stopContainer(containerId: string, timeout: number = 10): Promise<void> {
    logger.info(`Stopping container: ${containerId}`);
    
    try {
      const result = await this.executeDockerCommand(['stop', '--time', timeout.toString(), containerId]);
      
      if (result.exitCode !== 0) {
        logger.warn(`Failed to stop container gracefully, forcing: ${containerId}`);
        await this.executeDockerCommand(['kill', containerId]);
      }
      
      logger.info(`Container stopped: ${containerId}`);
      
    } catch (error) {
      logger.error(`Failed to stop container ${containerId}:`, error);
      throw error;
    }
  }
 
  /**
   * Remove a container with security cleanup
   */
  async removeContainer(containerId: string): Promise<void> {
    logger.info(`Removing secure container: ${containerId}`);
    
    try {
      // Stop security monitoring
      this.securityManager.stopResourceMonitoring(containerId);
      
      // First try to stop the container if it's running
      await this.stopContainer(containerId);
      
      // Remove the container
      const result = await this.executeDockerCommand(['rm', '--force', containerId]);
      
      if (result.exitCode !== 0) {
        logger.warn(`Failed to remove container ${containerId}: ${result.error}`);
      } else {
        logger.info(`Container removed: ${containerId}`);
      }
      
      // Cleanup secure temp directory
      const tempDir = this.containerTempDirs.get(containerId);
      if (tempDir) {
        await this.securityManager.cleanupSecureTempDir(tempDir);
        this.containerTempDirs.delete(containerId);
      }
      
      this.activeContainers.delete(containerId);
      
    } catch (error) {
      logger.error(`Failed to remove secure container ${containerId}:`, error);
      // Don't throw here, as this is cleanup
    }
  }
 
  /**
   * Copy file from container to host
   */
  async copyFromContainer(containerId: string, containerPath: string, hostPath: string): Promise<void> {
    logger.info(`Copying from container ${containerId}: ${containerPath} -> ${hostPath}`);
    
    try {
      // Ensure host directory exists
      const hostDir = join(hostPath, '..');
      await fs.mkdir(hostDir, { recursive: true });
      
      const result = await this.executeDockerCommand([
        'cp',
        `${containerId}:${containerPath}`,
        hostPath
      ]);
      
      if (result.exitCode !== 0) {
        throw new Error(`Failed to copy from container: ${result.error}`);
      }
      
      logger.info(`Successfully copied from container: ${containerPath}`);
      
    } catch (error) {
      logger.error(`Failed to copy from container ${containerId}:`, error);
      throw error;
    }
  }
 
  /**
   * Get container logs
   */
  async getContainerLogs(containerId: string): Promise<string> {
    try {
      const result = await this.executeDockerCommand(['logs', containerId]);
      return result.output;
    } catch (error) {
      logger.error(`Failed to get logs for container ${containerId}:`, error);
      return '';
    }
  }
 
  /**
   * Get security violations for monitoring
   */
  getSecurityViolations(): SecurityViolation[] {
    return this.securityManager.getViolations();
  }
 
  /**
   * Get resource usage for a container
   */
  async getResourceUsage(containerId: string) {
    return await this.securityManager.getResourceUsage(containerId);
  }
 
  /**
   * Clean up all active containers with security cleanup
   */
  async cleanup(): Promise<void> {
    logger.info('Cleaning up secure Docker manager...');
    
    const containerIds = Array.from(this.activeContainers);
    
    for (const containerId of containerIds) {
      await this.removeContainer(containerId);
    }
    
    // Cleanup security manager
    this.securityManager.cleanup();
    
    this.activeContainers.clear();
    this.containerTempDirs.clear();
    logger.info('Secure Docker manager cleanup completed');
  }
 
  /**
   * Execute a Docker command
   */
  private async executeDockerCommand(
    args: string[],
    options: ExecutionOptions = {}
  ): Promise<ExecutionResult> {
    return new Promise((resolve, reject) => {
      const process = spawn('docker', args, {
        stdio: ['pipe', 'pipe', 'pipe']
      });
 
      let output = '';
      let error = '';
      let timeoutId: NodeJS.Timeout | null = null;
 
      // Set up timeout if specified
      if (options.timeout) {
        timeoutId = setTimeout(() => {
          process.kill('SIGKILL');
          reject(new Error(`Command timed out after ${options.timeout}ms`));
        }, options.timeout);
      }
 
      // Collect stdout
      process.stdout.on('data', (data: Buffer) => {
        const chunk = data.toString();
        output += chunk;
        
        if (options.onOutput) {
          options.onOutput(chunk);
        }
      });
 
      // Collect stderr
      process.stderr.on('data', (data: Buffer) => {
        const chunk = data.toString();
        error += chunk;
        
        if (options.onOutput) {
          options.onOutput(chunk);
        }
      });
 
      // Handle process completion
      process.on('close', (code: number | null) => {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        
        resolve({
          exitCode: code || 0,
          output: output.trim(),
          error: error.trim()
        });
      });
 
      // Handle process errors
      process.on('error', (err: Error) => {
        if (timeoutId) {
          clearTimeout(timeoutId);
        }
        
        reject(err);
      });
    });
  }
}