All files / src/profiles project-loader.ts

100% Statements 113/113
95.23% Branches 60/63
100% Functions 6/6
100% Lines 112/112

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                              3x 3x 3x 3x               3x             3x     3x     3x                       3x 14x     14x 14x 13x 1x 1x     1x 1x     12x         12x 12x 12x 9x 9x 8x     4x 1x 1x 1x         11x 11x 11x 3x 3x 2x     9x 1x 1x 1x         10x 1x       1x     9x                 9x                       3x 4x 4x   4x   8x 8x 8x 2x           6x 6x 6x 1x 1x           5x     1x           3x 3x 3x       3x 1x     1x 1x             3x 1x 2x 2x 1x         3x                   3x       4x 4x     4x 2x 1x         4x 4x 2x 1x           4x                   3x       11x 11x   11x 5x 5x 1x   5x 1x 4x 1x 3x 1x   5x 1x   5x 1x   5x     11x 6x 6x 2x   6x 2x   6x 2x   6x 2x   6x     11x    
/**
 * Project-level configuration loader
 *
 * Loads configuration from .gitlab-mcp/ directory in a project repository.
 * Project configs provide:
 * - Scope restrictions (limit operations to specific projects)
 * - Feature overrides
 * - Tool selection
 *
 * Security notes:
 * - Project configs can only RESTRICT, never expand permissions
 * - No secrets in project files - auth comes from env/profiles
 * - Ignored in OAuth mode (server-side)
 */
 
import * as fs from "fs/promises";
import * as path from "path";
import * as yaml from "yaml";
import {
  ProjectConfig,
  ProjectPreset,
  ProjectProfile,
  ProjectPresetSchema,
  ProjectProfileSchema,
  ProfileValidationResult,
} from "./types";
import { logger } from "../logger";
 
// ============================================================================
// Constants
// ============================================================================
 
/** Directory name for project-level configs */
export const PROJECT_CONFIG_DIR = ".gitlab-mcp";
 
/** Preset file name (restrictions) */
export const PROJECT_PRESET_FILE = "preset.yaml";
 
/** Profile file name (tool selection) */
export const PROJECT_PROFILE_FILE = "profile.yaml";
 
// ============================================================================
// Project Config Loader
// ============================================================================
 
/**
 * Load project configuration from .gitlab-mcp/ directory
 *
 * @param repoPath Path to the repository root (directory containing .gitlab-mcp/)
 * @returns ProjectConfig or null if no config exists
 */
export async function loadProjectConfig(repoPath: string): Promise<ProjectConfig | null> {
  const configDir = path.join(repoPath, PROJECT_CONFIG_DIR);
 
  // Check if .gitlab-mcp/ directory exists
  try {
    const stat = await fs.stat(configDir);
    if (!stat.isDirectory()) {
      logger.warn({ path: configDir }, "Project config path exists but is not a directory");
      return null;
    }
  } catch {
    logger.debug({ path: configDir }, "No project config directory found");
    return null;
  }
 
  const config: ProjectConfig = {
    configPath: configDir,
  };
 
  // Load preset.yaml (restrictions)
  const presetPath = path.join(configDir, PROJECT_PRESET_FILE);
  try {
    const content = await fs.readFile(presetPath, "utf8");
    const parsed = yaml.parse(content) as unknown;
    config.preset = ProjectPresetSchema.parse(parsed);
    logger.debug({ path: presetPath }, "Loaded project preset");
  } catch (error) {
    // File doesn't exist - that's OK
    if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
      const message = error instanceof Error ? error.message : String(error);
      logger.error({ error: message, path: presetPath }, "Failed to parse project preset");
      throw new Error(`Invalid project preset at ${presetPath}: ${message}`);
    }
  }
 
  // Load profile.yaml (tool selection)
  const profilePath = path.join(configDir, PROJECT_PROFILE_FILE);
  try {
    const content = await fs.readFile(profilePath, "utf8");
    const parsed = yaml.parse(content) as unknown;
    config.profile = ProjectProfileSchema.parse(parsed);
    logger.debug({ path: profilePath }, "Loaded project profile");
  } catch (error) {
    // File doesn't exist - that's OK
    if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
      const message = error instanceof Error ? error.message : String(error);
      logger.error({ error: message, path: profilePath }, "Failed to parse project profile");
      throw new Error(`Invalid project profile at ${profilePath}: ${message}`);
    }
  }
 
  // Return null if neither file exists
  if (!config.preset && !config.profile) {
    logger.debug(
      { path: configDir },
      "Project config directory exists but contains no config files"
    );
    return null;
  }
 
  logger.info(
    {
      path: configDir,
      hasPreset: !!config.preset,
      hasProfile: !!config.profile,
    },
    "Loaded project configuration"
  );
 
  return config;
}
 
/**
 * Find project config by walking up directory tree
 *
 * Useful when running from a subdirectory of a repository.
 * Stops at filesystem root or when .git is found without .gitlab-mcp.
 *
 * @param startPath Starting directory path
 * @returns ProjectConfig or null if not found
 */
export async function findProjectConfig(startPath: string): Promise<ProjectConfig | null> {
  let currentPath = path.resolve(startPath);
  const root = path.parse(currentPath).root;
 
  while (currentPath !== root) {
    // Check if .gitlab-mcp/ exists at this level
    const configDir = path.join(currentPath, PROJECT_CONFIG_DIR);
    try {
      await fs.access(configDir);
      return loadProjectConfig(currentPath);
    } catch {
      // Directory doesn't exist, continue searching
    }
 
    // Stop if we hit a .git directory without finding .gitlab-mcp
    const gitDir = path.join(currentPath, ".git");
    try {
      await fs.access(gitDir);
      logger.debug({ path: currentPath }, "Found .git without .gitlab-mcp, stopping search");
      return null;
    } catch {
      // .git doesn't exist, continue up the tree
    }
 
    // Move up one directory
    currentPath = path.dirname(currentPath);
  }
 
  return null;
}
 
/**
 * Validate a project preset configuration
 */
export function validateProjectPreset(preset: ProjectPreset): ProfileValidationResult {
  const errors: string[] = [];
  const warnings: string[] = [];
 
  // Validate scope configuration
  // Note: Combining 'project' with 'projects' is already prevented by the Zod schema refinement
  if (preset.scope) {
    const { project, namespace, projects } = preset.scope;
 
    // Warn about broad namespace scope
    Eif (namespace && !project && !projects?.length) {
      warnings.push(
        `Scope restricts to namespace '${namespace}' - all projects in this group are allowed`
      );
    }
  }
 
  // Validate denied_actions format
  if (preset.denied_actions) {
    for (const action of preset.denied_actions) {
      const colonIndex = action.indexOf(":");
      if (colonIndex === -1) {
        errors.push(`Invalid denied_action format '${action}', expected 'tool:action'`);
      }
    }
  }
 
  return {
    valid: errors.length === 0,
    errors,
    warnings,
  };
}
 
/**
 * Validate a project profile configuration
 */
export function validateProjectProfile(
  profile: ProjectProfile,
  availablePresets: string[]
): ProfileValidationResult {
  const errors: string[] = [];
  const warnings: string[] = [];
 
  // Validate extends references valid preset
  if (profile.extends) {
    if (!availablePresets.includes(profile.extends)) {
      errors.push(`Unknown preset '${profile.extends}' in extends field`);
    }
  }
 
  // Warn about conflicting tool settings
  if (profile.additional_tools && profile.denied_tools) {
    const overlap = profile.additional_tools.filter(t => profile.denied_tools?.includes(t));
    if (overlap.length > 0) {
      warnings.push(
        `Tools appear in both additional_tools and denied_tools: ${overlap.join(", ")}`
      );
    }
  }
 
  return {
    valid: errors.length === 0,
    errors,
    warnings,
  };
}
 
/**
 * Get a summary of project configuration for display
 */
export function getProjectConfigSummary(config: ProjectConfig): {
  presetSummary: string | null;
  profileSummary: string | null;
} {
  let presetSummary: string | null = null;
  let profileSummary: string | null = null;
 
  if (config.preset) {
    const parts: string[] = [];
    if (config.preset.description) {
      parts.push(config.preset.description);
    }
    if (config.preset.scope?.project) {
      parts.push(`scope: ${config.preset.scope.project}`);
    } else if (config.preset.scope?.namespace) {
      parts.push(`scope: ${config.preset.scope.namespace}/*`);
    } else if (config.preset.scope?.projects) {
      parts.push(`scope: ${config.preset.scope.projects.length} projects`);
    }
    if (config.preset.read_only) {
      parts.push("read-only");
    }
    if (config.preset.denied_actions?.length) {
      parts.push(`${config.preset.denied_actions.length} denied actions`);
    }
    presetSummary = parts.join(", ") || "custom restrictions";
  }
 
  if (config.profile) {
    const parts: string[] = [];
    if (config.profile.description) {
      parts.push(config.profile.description);
    }
    if (config.profile.extends) {
      parts.push(`extends: ${config.profile.extends}`);
    }
    if (config.profile.additional_tools?.length) {
      parts.push(`+${config.profile.additional_tools.length} tools`);
    }
    if (config.profile.denied_tools?.length) {
      parts.push(`-${config.profile.denied_tools.length} tools`);
    }
    profileSummary = parts.join(", ") || "custom tool selection";
  }
 
  return { presetSummary, profileSummary };
}