All files / src/cli/docker docker-utils.ts

99.46% Statements 187/188
89.01% Branches 81/91
100% Functions 28/28
99.45% Lines 183/184

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 527 528 529        3x 3x 3x 3x 3x 3x                       3x 3x     8x         3x 47x           3x 3x 3x           3x 3x 3x           3x 3x 3x               11x           3x   11x 1x     1x     10x 10x 10x                               10x 4x     6x 6x   6x 1x     5x     5x 5x 5x 1x 4x 1x 3x 1x 2x 1x 1x 1x         5x 5x 1x     5x         5x                       3x 3x   3x               3x 2x       3x   3x           3x 14x                                   14x 1x                       1x 1x 1x         14x     6x 1x   5x     6x       6x       14x 1x 2x       14x           3x 12x       12x 12x       12x 1x           12x 1x       12x           3x 12x 12x   12x 6x     6x 6x 6x   5x                       1x             3x 7x   7x 3x     7x 7x 7x           3x 3x   3x 2x     3x 3x 3x           3x 13x     13x 13x 1x           12x 12x 1x           11x   11x 11x   11x           10x 8x         2x           1x                   3x 5x           3x 2x           3x 2x           3x 2x 2x 1x     1x           3x 4x 4x   4x 1x   3x   3x   3x 2x     3x   3x                 3x 1x           3x 3x     3x 3x 1x   2x     3x           3x 2x 2x   2x 1x     1x 1x           3x 3x           3x     3x     3x 1x     3x             3x 7x   7x 3x     7x   7x 3x     7x   1x 1x     7x 3x 3x      
/**
 * Docker utilities for gitlab-mcp container management
 */
 
import { spawnSync, spawn, ChildProcess } from "child_process";
import { randomBytes } from "crypto";
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "fs";
import { join } from "path";
import YAML from "yaml";
import {
  DockerConfig,
  DockerComposeFile,
  DockerStatusResult,
  DockerCommandResult,
  ContainerInfo,
  ContainerStatus,
  GitLabInstance,
  InstancesYaml,
  DEFAULT_DOCKER_CONFIG,
  getConfigDir,
} from "./types";
import { getContainerRuntime } from "./container-runtime";
import { expandPath } from "../utils/path-utils.js";
 
// Re-export expandPath for backwards compatibility with existing imports
export { expandPath } from "../utils/path-utils.js";
 
/**
 * Get expanded config directory path
 */
export function getExpandedConfigDir(): string {
  return expandPath(getConfigDir());
}
 
/**
 * Check if a container runtime (Docker/Podman) is installed
 */
export function isDockerInstalled(): boolean {
  const runtime = getContainerRuntime();
  return runtime.runtimeVersion !== undefined;
}
 
/**
 * Check if the container runtime daemon is running
 */
export function isDockerRunning(): boolean {
  const runtime = getContainerRuntime();
  return runtime.runtimeAvailable;
}
 
/**
 * Check if a compose tool is available for the detected runtime
 */
export function isComposeInstalled(): boolean {
  const runtime = getContainerRuntime();
  return runtime.composeCmd !== null;
}
 
/**
 * Validate container name format to prevent command injection
 */
function isValidContainerName(name: string): boolean {
  // Docker container names can only contain [a-zA-Z0-9][a-zA-Z0-9_.-]
  return /^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(name);
}
 
/**
 * Get container info
 */
export function getContainerInfo(containerName: string = "gitlab-mcp"): ContainerInfo | undefined {
  // Validate container name to prevent command injection
  if (!isValidContainerName(containerName)) {
    console.error(
      `Invalid container name: "${containerName}". Name must match [a-zA-Z0-9][a-zA-Z0-9_.-]*`
    );
    return undefined;
  }
 
  try {
    const runtime = getContainerRuntime();
    const result = spawnSync(
      runtime.runtimeCmd,
      [
        "ps",
        "-a",
        "--filter",
        `name=${containerName}`,
        "--format",
        "{{.ID}}|{{.Names}}|{{.Image}}|{{.Status}}|{{.Ports}}|{{.CreatedAt}}",
      ],
      {
        stdio: "pipe",
        encoding: "utf8",
      }
    );
 
    if (result.status !== 0 || !result.stdout.trim()) {
      return undefined;
    }
 
    const line = result.stdout.trim().split("\n")[0];
    const parts = line.split("|");
 
    if (parts.length < 6) {
      return undefined;
    }
 
    const [id, name, image, statusStr, ports, created] = parts;
 
    // Parse status
    let status: ContainerStatus = "exited";
    const statusLower = statusStr.toLowerCase();
    if (statusLower.includes("up")) {
      status = "running";
    } else if (statusLower.includes("paused")) {
      status = "paused";
    } else if (statusLower.includes("restarting")) {
      status = "restarting";
    } else if (statusLower.includes("created")) {
      status = "created";
    } else Eif (statusLower.includes("dead")) {
      status = "dead";
    }
 
    // Extract uptime from status string
    let uptime: string | undefined;
    const uptimeMatch = statusStr.match(/Up\s+(.+?)(?:\s*\(|$)/i);
    if (uptimeMatch) {
      uptime = uptimeMatch[1].trim();
    }
 
    return {
      id,
      name,
      image,
      status,
      ports: ports ? ports.split(",").map(p => p.trim()) : [],
      created,
      uptime,
    };
  } catch {
    return undefined;
  }
}
 
/**
 * Get Docker status
 */
export function getDockerStatus(containerName: string = "gitlab-mcp"): DockerStatusResult {
  const runtime = getContainerRuntime();
 
  const result: DockerStatusResult = {
    dockerInstalled: runtime.runtimeVersion !== undefined,
    dockerRunning: runtime.runtimeAvailable,
    composeInstalled: runtime.composeCmd !== null,
    instances: [],
    runtime,
  };
 
  if (result.dockerRunning) {
    result.container = getContainerInfo(containerName);
  }
 
  // Load instances from config
  result.instances = loadInstances();
 
  return result;
}
 
/**
 * Generate docker-compose.yml content
 */
export function generateDockerCompose(config: DockerConfig): string {
  const compose: DockerComposeFile = {
    version: "3.8",
    services: {
      "gitlab-mcp": {
        image: config.image,
        container_name: config.containerName,
        ports: [`\${PORT:-${config.port}}:3333`],
        environment: ["TRANSPORT=sse", "PORT=3333", `OAUTH_ENABLED=${config.oauthEnabled}`],
        volumes: ["gitlab-mcp-data:/data"],
        restart: "unless-stopped",
      },
    },
    volumes: {
      "gitlab-mcp-data": {},
    },
  };
 
  // Add compose-bundle postgres service (only when OAuth needs a database)
  if (config.deploymentType === "compose-bundle" && config.oauthEnabled) {
    compose.services.postgres = {
      image: "postgres:16-alpine",
      container_name: `${config.containerName}-db`,
      ports: [],
      environment: [
        "POSTGRES_USER=gitlab_mcp",
        "POSTGRES_PASSWORD=${POSTGRES_PASSWORD}",
        "POSTGRES_DB=gitlab_mcp",
      ],
      volumes: ["postgres-data:/var/lib/postgresql/data"],
      restart: "unless-stopped",
    };
    compose.services["gitlab-mcp"].depends_on = ["postgres"];
    Eif (compose.volumes) {
      compose.volumes["postgres-data"] = {};
    }
  }
 
  // Add OAuth-specific configuration
  if (config.oauthEnabled) {
    // Determine DATABASE_URL based on deployment type
    let databaseUrl: string;
    if (config.deploymentType === "compose-bundle") {
      databaseUrl = "postgresql://gitlab_mcp:${POSTGRES_PASSWORD}@postgres:5432/gitlab_mcp";
    } else {
      databaseUrl = config.databaseUrl ?? "file:/data/sessions.db";
    }
    // Reference secret via env var — actual value stored in .env file
    compose.services["gitlab-mcp"].environment.push(
      "OAUTH_SESSION_SECRET=${OAUTH_SESSION_SECRET}",
      `DATABASE_URL=${databaseUrl}`
    );
    compose.services["gitlab-mcp"].volumes.push("./instances.yml:/app/config/instances.yml:ro");
  }
 
  // Add tool configuration environment variables
  if (config.environment) {
    for (const [key, value] of Object.entries(config.environment)) {
      compose.services["gitlab-mcp"].environment.push(`${key}=${value}`);
    }
  }
 
  return YAML.stringify(compose);
}
 
/**
 * Generate instances.yml content
 */
export function generateInstancesYaml(instances: GitLabInstance[]): string {
  const yaml: InstancesYaml = {
    instances: {},
  };
 
  for (const instance of instances) {
    yaml.instances[instance.host] = {
      name: instance.name,
    };
 
    if (instance.oauth) {
      yaml.instances[instance.host].oauth = {
        client_id: instance.oauth.clientId,
        client_secret_env: instance.oauth.clientSecretEnv,
      };
    }
 
    if (instance.defaultPreset) {
      yaml.instances[instance.host].default_preset = instance.defaultPreset;
    }
  }
 
  return YAML.stringify(yaml);
}
 
/**
 * Load instances from config file
 */
export function loadInstances(): GitLabInstance[] {
  const configDir = getExpandedConfigDir();
  const instancesPath = join(configDir, "instances.yml");
 
  if (!existsSync(instancesPath)) {
    return [];
  }
 
  try {
    const content = readFileSync(instancesPath, "utf8");
    const yaml = YAML.parse(content) as InstancesYaml;
 
    return Object.entries(yaml.instances).map(([host, config]) => ({
      host,
      name: config.name,
      oauth: config.oauth
        ? {
            clientId: config.oauth.client_id,
            clientSecretEnv: config.oauth.client_secret_env,
          }
        : undefined,
      defaultPreset: config.default_preset,
    }));
  } catch {
    return [];
  }
}
 
/**
 * Save instances to config file
 */
export function saveInstances(instances: GitLabInstance[]): void {
  const configDir = getExpandedConfigDir();
 
  if (!existsSync(configDir)) {
    mkdirSync(configDir, { recursive: true });
  }
 
  const instancesPath = join(configDir, "instances.yml");
  const content = generateInstancesYaml(instances);
  writeFileSync(instancesPath, content, "utf8");
}
 
/**
 * Save docker-compose.yml to config directory
 */
export function saveDockerCompose(config: DockerConfig): void {
  const configDir = getExpandedConfigDir();
 
  if (!existsSync(configDir)) {
    mkdirSync(configDir, { recursive: true });
  }
 
  const composePath = join(configDir, "docker-compose.yml");
  const content = generateDockerCompose(config);
  writeFileSync(composePath, content, "utf8");
}
 
/**
 * Run docker compose command
 */
export function runComposeCommand(args: string[], configDir?: string): DockerCommandResult {
  const cwd = configDir ?? getExpandedConfigDir();
 
  // Check if docker-compose.yml exists
  const composePath = join(cwd, "docker-compose.yml");
  if (!existsSync(composePath)) {
    return {
      success: false,
      error: `docker-compose.yml not found in ${cwd}. Run 'gitlab-mcp docker init' first.`,
    };
  }
 
  const runtime = getContainerRuntime();
  if (!runtime.composeCmd) {
    return {
      success: false,
      error: "No compose tool available. Install docker-compose or podman-compose.",
    };
  }
 
  try {
    // Use the detected compose command
    const [composeExe, ...composePrefix] = runtime.composeCmd;
    const fullArgs = [...composePrefix, ...args];
 
    const result = spawnSync(composeExe, fullArgs, {
      cwd,
      stdio: "pipe",
      encoding: "utf8",
    });
 
    if (result.status === 0) {
      return {
        success: true,
        output: result.stdout,
      };
    } else {
      return {
        success: false,
        error: result.stderr || result.stdout || "Unknown error",
      };
    }
  } catch (error) {
    return {
      success: false,
      error: error instanceof Error ? error.message : String(error),
    };
  }
}
 
/**
 * Start container
 */
export function startContainer(): DockerCommandResult {
  return runComposeCommand(["up", "-d"]);
}
 
/**
 * Stop container
 */
export function stopContainer(): DockerCommandResult {
  return runComposeCommand(["down"]);
}
 
/**
 * Restart container
 */
export function restartContainer(): DockerCommandResult {
  return runComposeCommand(["restart"]);
}
 
/**
 * Pull latest image and restart
 */
export function upgradeContainer(): DockerCommandResult {
  const pullResult = runComposeCommand(["pull"]);
  if (!pullResult.success) {
    return pullResult;
  }
 
  return runComposeCommand(["up", "-d"]);
}
 
/**
 * Get container logs (returns process for streaming)
 */
export function tailLogs(follow: boolean = true, lines: number = 100): ChildProcess {
  const configDir = getExpandedConfigDir();
  const runtime = getContainerRuntime();
 
  if (!runtime.composeCmd) {
    throw new Error("No compose tool available. Install Docker Compose or podman-compose.");
  }
  const [composeExe, ...composePrefix] = runtime.composeCmd;
 
  const args = [...composePrefix, "logs"];
 
  if (follow) {
    args.push("-f");
  }
 
  args.push("--tail", String(lines));
 
  return spawn(composeExe, args, {
    cwd: configDir,
    stdio: "inherit",
  });
}
 
/**
 * Get container logs (non-streaming)
 */
export function getLogs(lines: number = 100): DockerCommandResult {
  return runComposeCommand(["logs", "--tail", String(lines)]);
}
 
/**
 * Add a GitLab instance to configuration
 */
export function addInstance(instance: GitLabInstance): void {
  const instances = loadInstances();
 
  // Check if already exists
  const existingIndex = instances.findIndex(i => i.host === instance.host);
  if (existingIndex >= 0) {
    instances[existingIndex] = instance;
  } else {
    instances.push(instance);
  }
 
  saveInstances(instances);
}
 
/**
 * Remove a GitLab instance from configuration
 */
export function removeInstance(host: string): boolean {
  const instances = loadInstances();
  const filteredInstances = instances.filter(i => i.host !== host);
 
  if (filteredInstances.length === instances.length) {
    return false; // Instance not found
  }
 
  saveInstances(filteredInstances);
  return true;
}
 
/**
 * Initialize Docker configuration
 */
export function initDockerConfig(config: Partial<DockerConfig> = {}): DockerConfig {
  const fullConfig: DockerConfig = {
    ...DEFAULT_DOCKER_CONFIG,
    ...config,
  };
 
  // Save docker-compose.yml
  saveDockerCompose(fullConfig);
 
  // Write .env file with secrets (restricted permissions)
  saveEnvFile(fullConfig);
 
  // Save instances if provided
  if (fullConfig.instances.length > 0) {
    saveInstances(fullConfig.instances);
  }
 
  return fullConfig;
}
 
/**
 * Write .env file with secrets for docker-compose environment variable references.
 * File is created with 0600 permissions to limit exposure.
 */
export function saveEnvFile(config: DockerConfig): void {
  const configDir = getExpandedConfigDir();
 
  if (!existsSync(configDir)) {
    mkdirSync(configDir, { recursive: true });
  }
 
  const lines: string[] = [];
 
  if (config.oauthSessionSecret) {
    lines.push(`OAUTH_SESSION_SECRET=${config.oauthSessionSecret}`);
  }
 
  if (config.deploymentType === "compose-bundle" && config.oauthEnabled) {
    // Generate a strong random postgres password for the bundled database
    const pgPassword = randomBytes(24).toString("base64url");
    lines.push(`POSTGRES_PASSWORD=${pgPassword}`);
  }
 
  if (lines.length > 0) {
    const envPath = join(configDir, ".env");
    writeFileSync(envPath, lines.join("\n") + "\n", { encoding: "utf8", mode: 0o600 });
  }
}