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 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 | /** * AI Fix Service - Claude Sonnet 4 powered autonomous vulnerability fixing * Premium service for generating and applying security fixes */ const axios = require('axios') const fs = require('fs-extra') const path = require('path') const chalk = require('chalk') const crypto = require('crypto') // const structlog = require('structlog') const logger = { info: (...args) => console.log('[INFO]', ...args), error: (...args) => console.error('[ERROR]', ...args), warn: (...args) => console.warn('[WARN]', ...args), debug: (...args) => console.log('[DEBUG]', ...args) } class AIFixService { constructor(model = 'claude-sonnet-4', config = {}) { this.model = model this.config = config this.anthropicApiKey = config.anthropic?.apiKey || process.env.ANTHROPIC_API_KEY this.vaultaceApiUrl = config.apiUrl || 'https://api.vaultace.com' if (!this.anthropicApiKey) { throw new Error('Anthropic API key required for autonomous fixing') } // Fix generation statistics this.stats = { fixes_generated: 0, fixes_applied: 0, fixes_failed: 0, tokens_used: 0 } } /** * Generate fix for a single vulnerability using Claude Sonnet 4 */ async generateFix(vulnerability, repoPath) { const startTime = Date.now() try { // Read the vulnerable file const fileContent = await fs.readFile(vulnerability.file, 'utf-8') const lines = fileContent.split('\n') // Get context around the vulnerability const contextLines = this.getContextLines(lines, vulnerability.line, 10) // Build comprehensive fix prompt const fixPrompt = await this.buildFixPrompt(vulnerability, contextLines, repoPath) // Call Claude Sonnet 4 for fix generation const aiResponse = await this.callClaudeSonnet4(fixPrompt) // Parse the fix response const fix = await this.parseFixResponse(aiResponse, vulnerability) // Validate the fix await this.validateFix(fix, vulnerability, fileContent) this.stats.fixes_generated++ this.stats.tokens_used += this.estimateTokens(fixPrompt + aiResponse) await logger.info('Fix generated successfully', { vulnerability_type: vulnerability.type, file: vulnerability.file, model: this.model, duration_ms: Date.now() - startTime }) return fix } catch (error) { this.stats.fixes_failed++ await logger.error('Fix generation failed', { vulnerability_type: vulnerability.type, file: vulnerability.file, error: error.message }) throw new Error(`Failed to generate fix: ${error.message}`) } } /** * Generate fixes for multiple vulnerabilities in batch */ async generateBatchFixes(vulnerabilities, repoPath) { const fixes = [] const batchSize = 5 // Process in small batches to avoid rate limits for (let i = 0; i < vulnerabilities.length; i += batchSize) { const batch = vulnerabilities.slice(i, i + batchSize) const batchPromises = batch.map(vuln => this.generateFix(vuln, repoPath).catch(error => ({ vulnerability: vuln, error: error.message, status: 'failed' })) ) const batchResults = await Promise.all(batchPromises) fixes.push(...batchResults) // Brief pause between batches if (i + batchSize < vulnerabilities.length) { await new Promise(resolve => setTimeout(resolve, 2000)) } } return fixes } /** * Apply a generated fix to the codebase */ async applyFix(fix) { try { const originalContent = await fs.readFile(fix.file_path, 'utf-8') // Apply the fix based on fix type let newContent if (fix.fix_type === 'line_replacement') { newContent = this.applyLineReplacement(originalContent, fix) } else if (fix.fix_type === 'block_replacement') { newContent = this.applyBlockReplacement(originalContent, fix) } else if (fix.fix_type === 'insertion') { newContent = this.applyInsertion(originalContent, fix) } else if (fix.fix_type === 'file_modification') { newContent = fix.new_content } else { throw new Error(`Unsupported fix type: ${fix.fix_type}`) } // Create backup const backupPath = `${fix.file_path}.vaultace-backup-${Date.now()}` await fs.copy(fix.file_path, backupPath) // Apply the fix await fs.writeFile(fix.file_path, newContent) // Verify fix was applied correctly await this.verifyFixApplication(fix, newContent) this.stats.fixes_applied++ await logger.info('Fix applied successfully', { file: fix.file_path, fix_type: fix.fix_type, vulnerability_type: fix.vulnerability_type, backup_path: backupPath }) return { ...fix, status: 'applied', backup_path: backupPath, applied_at: new Date().toISOString() } } catch (error) { await logger.error('Fix application failed', { file: fix.file_path, error: error.message }) throw new Error(`Failed to apply fix: ${error.message}`) } } /** * Build comprehensive prompt for Claude Sonnet 4 */ async buildFixPrompt(vulnerability, contextLines, repoPath) { // Analyze project structure for better context const projectContext = await this.analyzeProjectStructure(repoPath) return `You are an expert security engineer using Claude Sonnet 4 to autonomously fix code vulnerabilities. VULNERABILITY TO FIX: - Type: ${vulnerability.type} - Severity: ${vulnerability.severity} - File: ${vulnerability.file} - Line: ${vulnerability.line} - Description: ${vulnerability.description} PROJECT CONTEXT: - Framework: ${projectContext.framework} - Language: ${projectContext.language} - Dependencies: ${projectContext.dependencies.slice(0, 10).join(', ')} - Architecture: ${projectContext.architecture} VULNERABLE CODE CONTEXT: \`\`\`${projectContext.language} ${contextLines} \`\`\` CONSTITUTIONAL AI PRINCIPLES FOR FIXING: 1. **Be Helpful**: Generate working, secure code that resolves the vulnerability 2. **Be Harmless**: Don't break existing functionality or introduce new vulnerabilities 3. **Be Honest**: If a fix is complex/risky, recommend manual review SPECIFIC REQUIREMENTS: - Maintain existing code style and patterns - Preserve all existing functionality - Use established security patterns from the codebase - Add minimal, clean code without over-engineering - Include brief inline comments explaining security changes RESPONSE FORMAT (JSON): { "fix_type": "line_replacement|block_replacement|insertion|file_modification", "confidence": 0.0-1.0, "risk_level": "low|medium|high", "description": "Clear description of what the fix does", "rationale": "Why this fix resolves the vulnerability", "line_start": number, "line_end": number, "original_code": "code being replaced", "fixed_code": "new secure code", "additional_changes": [ { "file": "path/to/file", "change_type": "import|constant|function", "content": "additional code needed" } ], "testing_notes": "How to verify this fix works", "security_impact": "Security improvement provided" } Generate a secure, production-ready fix that follows security best practices.` } /** * Call Claude Sonnet 4 API for fix generation */ async callClaudeSonnet4(prompt) { try { const response = await axios.post( 'https://api.anthropic.com/v1/messages', { model: this.model === 'claude-sonnet-4' ? 'claude-3-5-sonnet-20241022' : 'claude-3-sonnet-20240229', max_tokens: 8000, messages: [ { role: 'user', content: prompt } ], temperature: 0.1 // Low temperature for consistent, safe fixes }, { headers: { 'Content-Type': 'application/json', 'x-api-key': this.anthropicApiKey, 'anthropic-version': '2023-06-01' } } ) return response.data.content[0].text } catch (error) { if (error.response?.status === 429) { throw new Error('Rate limit exceeded - too many fix requests') } else if (error.response?.status === 401) { throw new Error('Invalid Anthropic API key') } else { throw new Error(`Claude Sonnet 4 API error: ${error.message}`) } } } /** * Parse Claude Sonnet 4 response into structured fix */ async parseFixResponse(response, vulnerability) { try { // Extract JSON from response const jsonMatch = response.match(/\{[\s\S]*\}/); if (!jsonMatch) { throw new Error('No valid JSON fix found in AI response') } const fix = JSON.parse(jsonMatch[0]) // Validate required fields const requiredFields = ['fix_type', 'confidence', 'risk_level', 'description', 'fixed_code'] for (const field of requiredFields) { if (!fix[field]) { throw new Error(`Missing required field in fix: ${field}`) } } // Add metadata fix.vulnerability_id = vulnerability.id || crypto.randomUUID() fix.vulnerability_type = vulnerability.type fix.file_path = vulnerability.file fix.severity = vulnerability.severity fix.generated_at = new Date().toISOString() fix.model_used = this.model return fix } catch (error) { throw new Error(`Failed to parse AI fix response: ${error.message}`) } } /** * Validate that the generated fix is safe and reasonable */ async validateFix(fix, vulnerability, originalContent) { // Check confidence threshold if (fix.confidence < 0.7) { throw new Error(`Fix confidence too low: ${fix.confidence}`) } // Validate fix type const validFixTypes = ['line_replacement', 'block_replacement', 'insertion', 'file_modification'] if (!validFixTypes.includes(fix.fix_type)) { throw new Error(`Invalid fix type: ${fix.fix_type}`) } // Check for dangerous patterns in the fix const dangerousPatterns = [ /eval\s*\(/, /exec\s*\(/, /rm\s+-rf/, /sudo\s+/, /password\s*=\s*['"]/ ] for (const pattern of dangerousPatterns) { if (pattern.test(fix.fixed_code)) { throw new Error('Fix contains potentially dangerous code patterns') } } // Validate line numbers const totalLines = originalContent.split('\n').length if (fix.line_start < 1 || fix.line_start > totalLines) { throw new Error(`Invalid line number: ${fix.line_start}`) } return true } /** * Apply line replacement fix */ applyLineReplacement(content, fix) { const lines = content.split('\n') // Replace specific lines for (let i = fix.line_start - 1; i < fix.line_end; i++) { if (i < lines.length) { lines[i] = fix.fixed_code } } return lines.join('\n') } /** * Apply block replacement fix */ applyBlockReplacement(content, fix) { const lines = content.split('\n') const before = lines.slice(0, fix.line_start - 1) const after = lines.slice(fix.line_end) const fixedLines = fix.fixed_code.split('\n') return [...before, ...fixedLines, ...after].join('\n') } /** * Apply insertion fix */ applyInsertion(content, fix) { const lines = content.split('\n') const insertionPoint = fix.line_start - 1 const fixedLines = fix.fixed_code.split('\n') lines.splice(insertionPoint, 0, ...fixedLines) return lines.join('\n') } /** * Get context lines around vulnerability */ getContextLines(lines, vulnLine, contextSize = 10) { const start = Math.max(0, vulnLine - contextSize - 1) const end = Math.min(lines.length, vulnLine + contextSize) const contextLines = [] for (let i = start; i < end; i++) { const lineNumber = i + 1 const marker = lineNumber === vulnLine ? '>>> ' : ' ' contextLines.push(`${marker}${lineNumber}: ${lines[i]}`) } return contextLines.join('\n') } /** * Analyze project structure for better context */ async analyzeProjectStructure(repoPath) { const context = { framework: 'unknown', language: 'unknown', dependencies: [], architecture: 'unknown' } try { // Check for package.json (Node.js) const packageJsonPath = path.join(repoPath, 'package.json') if (await fs.exists(packageJsonPath)) { const pkg = await fs.readJson(packageJsonPath) context.language = 'javascript' context.dependencies = Object.keys(pkg.dependencies || {}) // Detect framework if (context.dependencies.includes('react')) { context.framework = 'react' } else if (context.dependencies.includes('next')) { context.framework = 'nextjs' } else if (context.dependencies.includes('express')) { context.framework = 'express' } } // Check for requirements.txt (Python) const requirementsPath = path.join(repoPath, 'requirements.txt') if (await fs.exists(requirementsPath)) { const requirements = await fs.readFile(requirementsPath, 'utf-8') context.language = 'python' context.dependencies = requirements.split('\n') .filter(line => line.trim()) .map(line => line.split('==')[0].split('>=')[0].split('~=')[0]) // Detect Python framework if (context.dependencies.includes('fastapi')) { context.framework = 'fastapi' } else if (context.dependencies.includes('django')) { context.framework = 'django' } else if (context.dependencies.includes('flask')) { context.framework = 'flask' } } // Check for Cargo.toml (Rust) const cargoPath = path.join(repoPath, 'Cargo.toml') if (await fs.exists(cargoPath)) { context.language = 'rust' context.framework = 'rust' } } catch (error) { await logger.warning('Project analysis failed', { error: error.message }) } return context } /** * Verify fix was applied correctly */ async verifyFixApplication(fix, newContent) { // Basic verification that the fix was applied const lines = newContent.split('\n') const targetLine = lines[fix.line_start - 1] // Check if the vulnerable pattern is still present if (fix.original_code && newContent.includes(fix.original_code)) { throw new Error('Original vulnerable code still present after fix') } // Check if the fixed code was applied if (fix.fixed_code && !newContent.includes(fix.fixed_code.trim())) { throw new Error('Fixed code was not properly applied') } return true } /** * Generate fix for single vulnerability by ID (for API endpoint) */ async generateSingleFix(vulnerabilityId) { try { // In a real implementation, this would fetch vulnerability from database throw new Error('Single vulnerability fixing not yet implemented') } catch (error) { throw new Error(`Failed to generate single fix: ${error.message}`) } } /** * Estimate token usage for cost tracking */ estimateTokens(text) { // Rough estimation: ~4 characters per token return Math.ceil(text.length / 4) } /** * Get fixing statistics */ getStats() { return { ...this.stats, success_rate: this.stats.fixes_generated > 0 ? (this.stats.fixes_applied / this.stats.fixes_generated * 100).toFixed(1) + '%' : '0%' } } /** * Reset statistics */ resetStats() { this.stats = { fixes_generated: 0, fixes_applied: 0, fixes_failed: 0, tokens_used: 0 } } } /** * Vulnerability-specific fix templates and strategies */ class FixTemplates { static getFixStrategy(vulnerabilityType) { const strategies = { 'exposed_secret': { approach: 'environment_variable_replacement', risk_level: 'low', auto_approvable: true, template: 'Replace hardcoded secret with environment variable lookup' }, 'sql_injection': { approach: 'parameterized_query_conversion', risk_level: 'medium', auto_approvable: true, template: 'Convert string concatenation to parameterized query' }, 'xss_vulnerability': { approach: 'input_sanitization', risk_level: 'medium', auto_approvable: true, template: 'Add input sanitization and output encoding' }, 'path_traversal': { approach: 'path_validation', risk_level: 'medium', auto_approvable: true, template: 'Add path validation and normalization' }, 'client_side_auth_bypass': { approach: 'server_side_validation', risk_level: 'high', auto_approvable: false, template: 'Move authentication logic to server-side' }, 'insecure_deserialization': { approach: 'safe_deserialization', risk_level: 'high', auto_approvable: false, template: 'Replace unsafe deserialization with safe alternatives' } } return strategies[vulnerabilityType] || { approach: 'manual_review_required', risk_level: 'high', auto_approvable: false, template: 'Complex vulnerability requiring manual analysis' } } } module.exports = { AIFixService, FixTemplates } |