All files / agent/src/config validation.ts

78.52% Statements 351/447
86.08% Branches 99/115
100% Functions 14/14
78.52% Lines 351/447

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 4471x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 1x 1x 54x 54x 54x 54x 54x 54x 54x 54x 216x 10x 10x 10x 10x 10x 10x 216x 54x 1x 1x 54x 54x 3x 3x 3x 3x 3x 3x 54x 54x 54x             54x 54x             54x 54x             54x 54x 54x 1x 1x 1x 1x 1x 1x 54x 54x 1x 1x 1x 1x 1x 1x 54x 54x 54x 1x 1x 1x 1x 1x 54x             54x 54x 54x 1x 1x 1x 1x 1x 1x 54x 1x 1x 54x 54x 1x 1x 1x 1x 1x 1x 54x 54x 1x 1x 1x 1x 1x 1x 54x 54x             54x 54x 54x 1x 1x 1x 1x 1x 1x 54x 54x             54x 54x 54x             54x 54x 54x 1x 1x 1x 1x 1x 1x 54x 54x 54x 1x 1x 1x 1x 1x 1x 54x 54x 54x 8x 8x 8x 8x 8x 8x 54x 1x 1x 54x 39x 39x 39x 39x 54x 1x 1x 1x 1x 1x 1x 39x 39x 54x 1x 1x 1x 1x 1x 1x 39x 39x 54x 6x 6x 6x 6x 6x 6x 39x 39x 54x 6x 6x 6x 6x 6x 6x 39x 39x 54x 1x 1x 1x 1x 1x 54x 38x 3x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 38x 38x 54x 1x 1x 54x 54x 16x 54x             16x 54x             16x 54x             16x 54x             54x 1x 1x 54x 54x 20x 54x 1x 1x 1x 1x 1x 1x 20x 54x 1x 1x 1x 1x 1x 1x 20x 54x 1x 1x 1x 1x 1x 1x 20x 22x 2x 2x 54x 1x 1x 2x 1x 1x 1x 1x 1x 1x 2x 2x             2x 2x             2x 1x 1x 54x 54x 16x 54x             16x 54x             54x 1x 1x 54x 54x 15x 54x             54x 1x 1x 1x 9x 9x 9x 1x 1x 53x 53x 53x 53x 3x 3x 53x 1x 1x 39x 39x 1x 1x 39x 39x 39x 1x
/**
 * Configuration Validation
 * 
 * Validates agent configuration against schema and business rules
 * Requirements: 1.1, 1.2
 */
 
import { AgentConfig, ConfigValidationError, ConfigValidationResult, AcceptanceRules, ResourceGovernance, QuietHoursConfig, CacheConfig, ExecutionConfig } from './types.js';
 
export class ConfigValidator {
  /**
   * Validates the complete agent configuration
   */
  static validate(config: Partial<AgentConfig>): ConfigValidationResult {
    const errors: ConfigValidationError[] = [];
 
    // Required fields validation
    this.validateRequiredFields(config, errors);
    
    // Type and format validation
    this.validateTypes(config, errors);
    
    // Business rules validation
    this.validateBusinessRules(config, errors);
    
    // Docker configuration validation
    this.validateDockerConfig(config, errors);
 
    // Enhanced configuration validation
    this.validateAcceptanceRules(config, errors);
    this.validateResourceGovernance(config, errors);
    this.validateCacheConfig(config, errors);
    this.validateExecutionConfig(config, errors);
 
    return {
      isValid: errors.length === 0,
      errors
    };
  }
 
  private static validateRequiredFields(config: Partial<AgentConfig>, errors: ConfigValidationError[]): void {
    const requiredFields: (keyof AgentConfig)[] = [
      'platformUrl',
      'apiKey',
      'agentId',
      'name'
    ];
 
    for (const field of requiredFields) {
      if (!config[field]) {
        errors.push({
          field,
          message: `${field} is required`,
          value: config[field]
        });
      }
    }
  }
 
  private static validateTypes(config: Partial<AgentConfig>, errors: ConfigValidationError[]): void {
    // URL validation
    if (config.platformUrl && !this.isValidUrl(config.platformUrl)) {
      errors.push({
        field: 'platformUrl',
        message: 'platformUrl must be a valid URL',
        value: config.platformUrl
      });
    }
 
    // String validations
    if (config.apiKey && typeof config.apiKey !== 'string') {
      errors.push({
        field: 'apiKey',
        message: 'apiKey must be a string',
        value: config.apiKey
      });
    }
 
    if (config.agentId && typeof config.agentId !== 'string') {
      errors.push({
        field: 'agentId',
        message: 'agentId must be a string',
        value: config.agentId
      });
    }
 
    if (config.name && typeof config.name !== 'string') {
      errors.push({
        field: 'name',
        message: 'name must be a string',
        value: config.name
      });
    }
 
    // Number validations
    if (config.maxConcurrentJobs !== undefined && (!Number.isInteger(config.maxConcurrentJobs) || config.maxConcurrentJobs < 1)) {
      errors.push({
        field: 'maxConcurrentJobs',
        message: 'maxConcurrentJobs must be a positive integer',
        value: config.maxConcurrentJobs
      });
    }
 
    if (config.heartbeatInterval !== undefined && (!Number.isInteger(config.heartbeatInterval) || config.heartbeatInterval < 5)) {
      errors.push({
        field: 'heartbeatInterval',
        message: 'heartbeatInterval must be an integer >= 5 seconds',
        value: config.heartbeatInterval
      });
    }
 
    // Array validations
    if (config.tags && !Array.isArray(config.tags)) {
      errors.push({
        field: 'tags',
        message: 'tags must be an array of strings',
        value: config.tags
      });
    } else if (config.tags && !config.tags.every(tag => typeof tag === 'string')) {
      errors.push({
        field: 'tags',
        message: 'all tags must be strings',
        value: config.tags
      });
    }
 
    // Log level validation
    if (config.logLevel && !['debug', 'info', 'warn', 'error'].includes(config.logLevel)) {
      errors.push({
        field: 'logLevel',
        message: 'logLevel must be one of: debug, info, warn, error',
        value: config.logLevel
      });
    }
  }
 
  private static validateBusinessRules(config: Partial<AgentConfig>, errors: ConfigValidationError[]): void {
    // Resource usage limits
    if (config.maxMemoryUsage !== undefined && (config.maxMemoryUsage < 10 || config.maxMemoryUsage > 95)) {
      errors.push({
        field: 'maxMemoryUsage',
        message: 'maxMemoryUsage must be between 10 and 95 percent',
        value: config.maxMemoryUsage
      });
    }
 
    if (config.maxCpuUsage !== undefined && (config.maxCpuUsage < 10 || config.maxCpuUsage > 95)) {
      errors.push({
        field: 'maxCpuUsage',
        message: 'maxCpuUsage must be between 10 and 95 percent',
        value: config.maxCpuUsage
      });
    }
 
    if (config.maxDiskUsage !== undefined && (config.maxDiskUsage < 50 || config.maxDiskUsage > 95)) {
      errors.push({
        field: 'maxDiskUsage',
        message: 'maxDiskUsage must be between 50 and 95 percent',
        value: config.maxDiskUsage
      });
    }
 
    // Timeout validations
    if (config.jobTimeoutMinutes !== undefined && (config.jobTimeoutMinutes < 1 || config.jobTimeoutMinutes > 480)) {
      errors.push({
        field: 'jobTimeoutMinutes',
        message: 'jobTimeoutMinutes must be between 1 and 480 minutes (8 hours)',
        value: config.jobTimeoutMinutes
      });
    }
 
    if (config.connectionTimeoutSeconds !== undefined && (config.connectionTimeoutSeconds < 5 || config.connectionTimeoutSeconds > 300)) {
      errors.push({
        field: 'connectionTimeoutSeconds',
        message: 'connectionTimeoutSeconds must be between 5 and 300 seconds',
        value: config.connectionTimeoutSeconds
      });
    }
 
    // Log retention validation
    if (config.logRetentionDays !== undefined && (config.logRetentionDays < 1 || config.logRetentionDays > 90)) {
      errors.push({
        field: 'logRetentionDays',
        message: 'logRetentionDays must be between 1 and 90 days',
        value: config.logRetentionDays
      });
    }
 
    // Repository list validations
    if (config.allowedRepositories && config.blockedRepositories) {
      errors.push({
        field: 'allowedRepositories',
        message: 'Cannot specify both allowedRepositories and blockedRepositories',
        value: { allowed: config.allowedRepositories, blocked: config.blockedRepositories }
      });
    }
 
    // Agent name validation
    if (config.name && (config.name.length < 1 || config.name.length > 100)) {
      errors.push({
        field: 'name',
        message: 'name must be between 1 and 100 characters',
        value: config.name
      });
    }
 
    // API key validation
    if (config.apiKey && config.apiKey.length < 10) {
      errors.push({
        field: 'apiKey',
        message: 'apiKey appears to be too short (minimum 10 characters)',
        value: config.apiKey
      });
    }
  }
 
  private static validateDockerConfig(config: Partial<AgentConfig>, errors: ConfigValidationError[]): void {
    if (!config.dockerConfig) return;
 
    const dockerConfig = config.dockerConfig;
 
    // Base image validation
    if (!dockerConfig.baseImage || typeof dockerConfig.baseImage !== 'string') {
      errors.push({
        field: 'dockerConfig.baseImage',
        message: 'dockerConfig.baseImage must be a non-empty string',
        value: dockerConfig.baseImage
      });
    }
 
    // Network mode validation
    if (!['none', 'bridge'].includes(dockerConfig.networkMode)) {
      errors.push({
        field: 'dockerConfig.networkMode',
        message: 'dockerConfig.networkMode must be "none" or "bridge"',
        value: dockerConfig.networkMode
      });
    }
 
    // Memory limit validation
    if (!this.isValidMemoryLimit(dockerConfig.memoryLimit)) {
      errors.push({
        field: 'dockerConfig.memoryLimit',
        message: 'dockerConfig.memoryLimit must be a valid memory specification (e.g., "1g", "512m")',
        value: dockerConfig.memoryLimit
      });
    }
 
    // CPU limit validation
    if (!this.isValidCpuLimit(dockerConfig.cpuLimit)) {
      errors.push({
        field: 'dockerConfig.cpuLimit',
        message: 'dockerConfig.cpuLimit must be a valid CPU specification (e.g., "1.0", "0.5")',
        value: dockerConfig.cpuLimit
      });
    }
 
    // Volume mounts validation
    if (!Array.isArray(dockerConfig.volumeMounts)) {
      errors.push({
        field: 'dockerConfig.volumeMounts',
        message: 'dockerConfig.volumeMounts must be an array',
        value: dockerConfig.volumeMounts
      });
    } else {
      dockerConfig.volumeMounts.forEach((mount, index) => {
        if (!mount.hostPath || typeof mount.hostPath !== 'string') {
          errors.push({
            field: `dockerConfig.volumeMounts[${index}].hostPath`,
            message: 'hostPath must be a non-empty string',
            value: mount.hostPath
          });
        }
 
        if (!mount.containerPath || typeof mount.containerPath !== 'string') {
          errors.push({
            field: `dockerConfig.volumeMounts[${index}].containerPath`,
            message: 'containerPath must be a non-empty string',
            value: mount.containerPath
          });
        }
 
        if (typeof mount.readOnly !== 'boolean') {
          errors.push({
            field: `dockerConfig.volumeMounts[${index}].readOnly`,
            message: 'readOnly must be a boolean',
            value: mount.readOnly
          });
        }
      });
    }
  }
 
  private static validateAcceptanceRules(config: Partial<AgentConfig>, errors: ConfigValidationError[]): void {
    const rules = config.acceptanceRules;
    if (!rules) return;
 
    if (rules.maxJobDurationMinutes !== undefined && (rules.maxJobDurationMinutes < 1 || rules.maxJobDurationMinutes > 1440)) {
      errors.push({
        field: 'acceptanceRules.maxJobDurationMinutes',
        message: 'maxJobDurationMinutes must be between 1 and 1440 (24 hours)',
        value: rules.maxJobDurationMinutes
      });
    }
 
    if (rules.allowedRecipes && !Array.isArray(rules.allowedRecipes)) {
      errors.push({
        field: 'acceptanceRules.allowedRecipes',
        message: 'allowedRecipes must be an array of glob patterns',
        value: rules.allowedRecipes
      });
    }
 
    if (rules.blockedRecipes && !Array.isArray(rules.blockedRecipes)) {
      errors.push({
        field: 'acceptanceRules.blockedRecipes',
        message: 'blockedRecipes must be an array of glob patterns',
        value: rules.blockedRecipes
      });
    }
 
    if (rules.allowedRepositories && !Array.isArray(rules.allowedRepositories)) {
      errors.push({
        field: 'acceptanceRules.allowedRepositories',
        message: 'allowedRepositories must be an array of glob patterns',
        value: rules.allowedRepositories
      });
    }
  }
 
  private static validateResourceGovernance(config: Partial<AgentConfig>, errors: ConfigValidationError[]): void {
    const rg = config.resourceGovernance;
    if (!rg) return;
 
    if (rg.maxCpuPercent !== undefined && (rg.maxCpuPercent < 1 || rg.maxCpuPercent > 100)) {
      errors.push({
        field: 'resourceGovernance.maxCpuPercent',
        message: 'maxCpuPercent must be between 1 and 100',
        value: rg.maxCpuPercent
      });
    }
 
    if (rg.maxMemoryPercent !== undefined && (rg.maxMemoryPercent < 1 || rg.maxMemoryPercent > 100)) {
      errors.push({
        field: 'resourceGovernance.maxMemoryPercent',
        message: 'maxMemoryPercent must be between 1 and 100',
        value: rg.maxMemoryPercent
      });
    }
 
    if (rg.reservedDiskGB !== undefined && rg.reservedDiskGB < 0) {
      errors.push({
        field: 'resourceGovernance.reservedDiskGB',
        message: 'reservedDiskGB must be >= 0',
        value: rg.reservedDiskGB
      });
    }
 
    if (rg.quietHours) {
      this.validateQuietHours(rg.quietHours, errors);
    }
  }
 
  private static validateQuietHours(qh: QuietHoursConfig, errors: ConfigValidationError[]): void {
    if (qh.schedule && !this.isValidQuietHoursSchedule(qh.schedule)) {
      errors.push({
        field: 'resourceGovernance.quietHours.schedule',
        message: 'schedule must be in "HH:MM-HH:MM" format (24h)',
        value: qh.schedule
      });
    }
 
    if (qh.maxConcurrentJobs !== undefined && (qh.maxConcurrentJobs < 0 || !Number.isInteger(qh.maxConcurrentJobs))) {
      errors.push({
        field: 'resourceGovernance.quietHours.maxConcurrentJobs',
        message: 'maxConcurrentJobs must be a non-negative integer',
        value: qh.maxConcurrentJobs
      });
    }
 
    if (qh.maxCpuPercent !== undefined && (qh.maxCpuPercent < 1 || qh.maxCpuPercent > 100)) {
      errors.push({
        field: 'resourceGovernance.quietHours.maxCpuPercent',
        message: 'maxCpuPercent must be between 1 and 100',
        value: qh.maxCpuPercent
      });
    }
  }
 
  private static validateCacheConfig(config: Partial<AgentConfig>, errors: ConfigValidationError[]): void {
    const cc = config.cacheConfig;
    if (!cc) return;
 
    if (cc.maxSizeGB !== undefined && cc.maxSizeGB < 0) {
      errors.push({
        field: 'cacheConfig.maxSizeGB',
        message: 'maxSizeGB must be >= 0',
        value: cc.maxSizeGB
      });
    }
 
    if (cc.strategy && !['lru', 'fifo', 'lfu'].includes(cc.strategy)) {
      errors.push({
        field: 'cacheConfig.strategy',
        message: 'strategy must be one of: lru, fifo, lfu',
        value: cc.strategy
      });
    }
  }
 
  private static validateExecutionConfig(config: Partial<AgentConfig>, errors: ConfigValidationError[]): void {
    const ec = config.executionConfig;
    if (!ec) return;
 
    if (ec.defaultMode && !['docker', 'native', 'auto'].includes(ec.defaultMode)) {
      errors.push({
        field: 'executionConfig.defaultMode',
        message: 'defaultMode must be one of: docker, native, auto',
        value: ec.defaultMode
      });
    }
  }
 
  /** Validates "HH:MM-HH:MM" format */
  static isValidQuietHoursSchedule(schedule: string): boolean {
    const pattern = /^([01]\d|2[0-3]):[0-5]\d-([01]\d|2[0-3]):[0-5]\d$/;
    return pattern.test(schedule);
  }
 
  private static isValidUrl(url: string): boolean {
    try {
      new URL(url);
      return true;
    } catch {
      return false;
    }
  }
 
  private static isValidMemoryLimit(limit: string): boolean {
    return /^\d+[kmg]$/i.test(limit);
  }
 
  private static isValidCpuLimit(limit: string): boolean {
    const num = parseFloat(limit);
    return !isNaN(num) && num > 0 && num <= 32;
  }
}