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 | /** * Approval Workflow Service - Manage fix approvals and risk assessment * Handles automatic vs manual approval decisions for autonomous fixes */ const inquirer = require('inquirer') const chalk = require('chalk') const { table } = require('table') const fs = require('fs-extra') const path = require('path') // 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 ApprovalWorkflow { constructor(config = {}) { this.config = config this.approvalPolicies = this.loadApprovalPolicies(config) } /** * Load approval policies from configuration */ loadApprovalPolicies(config) { return { // Default approval policies automatic: { max_risk_level: 'low', allowed_types: [ 'exposed_secret', 'debug_statement', 'console_log_exposure', 'hardcoded_password', 'insecure_import' ], max_lines_changed: 10, exclude_files: ['auth*', 'security*', 'admin*'] }, hybrid: { max_risk_level: 'medium', allowed_types: [ 'exposed_secret', 'sql_injection', 'xss_vulnerability', 'path_traversal', 'insecure_import', 'debug_statement' ], max_lines_changed: 25, exclude_files: ['auth*', 'security*'] }, manual: { max_risk_level: 'critical', allowed_types: [], // All types require manual approval max_lines_changed: 1000, exclude_files: [] }, ...config.approval_policies // Override with user config } } /** * Determine if fix should be auto-approved */ async shouldAutoApprove(fix, policy = 'hybrid') { const policyConfig = this.approvalPolicies[policy] if (!policyConfig) { await logger.warning('Unknown approval policy, defaulting to manual', { policy }) return false } // Manual policy never auto-approves if (policy === 'manual') { return false } try { // Check risk level if (!this.isRiskLevelAllowed(fix.risk_level, policyConfig.max_risk_level)) { await logger.info('Fix rejected: risk level too high', { fix_risk: fix.risk_level, max_allowed: policyConfig.max_risk_level }) return false } // Check vulnerability type if (policyConfig.allowed_types.length > 0 && !policyConfig.allowed_types.includes(fix.vulnerability_type)) { await logger.info('Fix rejected: vulnerability type not auto-approvable', { type: fix.vulnerability_type, allowed_types: policyConfig.allowed_types }) return false } // Check file exclusions if (this.isFileExcluded(fix.file_path, policyConfig.exclude_files)) { await logger.info('Fix rejected: file in exclusion list', { file: fix.file_path, excluded_patterns: policyConfig.exclude_files }) return false } // Check lines changed const linesChanged = this.calculateLinesChanged(fix) if (linesChanged > policyConfig.max_lines_changed) { await logger.info('Fix rejected: too many lines changed', { lines_changed: linesChanged, max_allowed: policyConfig.max_lines_changed }) return false } // Check confidence threshold if (fix.confidence < 0.8) { await logger.info('Fix rejected: confidence too low', { confidence: fix.confidence }) return false } return true } catch (error) { await logger.error('Auto-approval check failed', { error: error.message }) return false // Default to manual approval on error } } /** * Process batch of fixes through approval workflow */ async processBatchApproval(fixes, policy = 'hybrid') { const results = { auto_approved: [], manual_review: [], rejected: [] } for (const fix of fixes) { if (await this.shouldAutoApprove(fix, policy)) { results.auto_approved.push(fix) } else { results.manual_review.push(fix) } } await logger.info('Batch approval processing completed', { total_fixes: fixes.length, auto_approved: results.auto_approved.length, manual_review: results.manual_review.length, policy: policy }) return results } /** * Interactive manual approval process */ async interactiveApproval(pendingFixes) { if (pendingFixes.length === 0) { return [] } console.log(chalk.bold('\nš MANUAL APPROVAL REQUIRED')) console.log(chalk.yellow(`${pendingFixes.length} fixes need your review`)) console.log('ā'.repeat(40)) const approvedFixes = [] for (let i = 0; i < pendingFixes.length; i++) { const fix = pendingFixes[i] console.log(chalk.bold(`\nš Fix ${i + 1}/${pendingFixes.length}`)) await this.displayFixDetails(fix) const { action } = await inquirer.prompt([{ type: 'list', name: 'action', message: 'What would you like to do?', choices: [ { name: 'ā Approve and apply fix', value: 'approve' }, { name: 'āļø Edit fix before applying', value: 'edit' }, { name: 'ā Reject this fix', value: 'reject' }, { name: 'āļø Skip for now', value: 'skip' }, { name: 'š Cancel remaining reviews', value: 'cancel' } ] }]) if (action === 'approve') { approvedFixes.push({ ...fix, approval_status: 'approved' }) console.log(chalk.green('ā Fix approved')) } else if (action === 'edit') { const editedFix = await this.interactiveFixEdit(fix) if (editedFix) { approvedFixes.push({ ...editedFix, approval_status: 'approved_edited' }) console.log(chalk.green('ā Edited fix approved')) } } else if (action === 'reject') { console.log(chalk.red('ā Fix rejected')) } else if (action === 'skip') { console.log(chalk.gray('āļø Fix skipped')) } else if (action === 'cancel') { console.log(chalk.yellow('š Approval process cancelled')) break } } return approvedFixes } /** * Display detailed fix information for manual review */ async displayFixDetails(fix) { console.log(`${chalk.bold('Vulnerability:')} ${fix.vulnerability_type}`) console.log(`${chalk.bold('File:')} ${fix.file_path}`) console.log(`${chalk.bold('Severity:')} ${this.getSeverityColor(fix.severity)(fix.severity)}`) console.log(`${chalk.bold('Risk Level:')} ${fix.risk_level}`) console.log(`${chalk.bold('Confidence:')} ${(fix.confidence * 100).toFixed(1)}%`) console.log(chalk.bold('\nFix Description:')) console.log(chalk.gray(fix.description)) console.log(chalk.bold('\nCode Changes:')) console.log(chalk.red('- ' + fix.original_code)) console.log(chalk.green('+ ' + fix.fixed_code)) if (fix.additional_changes?.length > 0) { console.log(chalk.bold('\nAdditional Changes:')) fix.additional_changes.forEach(change => { console.log(` ${change.file}: ${change.change_type}`) }) } console.log(chalk.bold('\nSecurity Impact:')) console.log(chalk.blue(fix.security_impact)) } /** * Interactive fix editing */ async interactiveFixEdit(fix) { console.log(chalk.bold('\nāļø EDIT FIX')) console.log('ā'.repeat(20)) const { editChoice } = await inquirer.prompt([{ type: 'list', name: 'editChoice', message: 'What would you like to edit?', choices: [ { name: 'Edit the fixed code', value: 'code' }, { name: 'Edit the description', value: 'description' }, { name: 'Cancel editing', value: 'cancel' } ] }]) if (editChoice === 'cancel') { return null } if (editChoice === 'code') { const { newCode } = await inquirer.prompt([{ type: 'editor', name: 'newCode', message: 'Edit the fixed code:', default: fix.fixed_code }]) return { ...fix, fixed_code: newCode, edited: true, original_ai_code: fix.fixed_code } } if (editChoice === 'description') { const { newDescription } = await inquirer.prompt([{ type: 'input', name: 'newDescription', message: 'Edit fix description:', default: fix.description }]) return { ...fix, description: newDescription, edited: true } } return fix } /** * Generate approval summary report */ generateApprovalSummary(fixes, approvedFixes) { const summary = { total_fixes: fixes.length, auto_approved: fixes.filter(f => f.auto_applied).length, manually_approved: approvedFixes.filter(f => f.approval_status === 'approved').length, edited_and_approved: approvedFixes.filter(f => f.approval_status === 'approved_edited').length, rejected: fixes.length - approvedFixes.length, approval_rate: ((approvedFixes.length / fixes.length) * 100).toFixed(1) + '%' } return summary } /** * Utility methods */ isRiskLevelAllowed(fixRisk, maxAllowed) { const riskLevels = ['low', 'medium', 'high', 'critical'] const fixIndex = riskLevels.indexOf(fixRisk) const maxIndex = riskLevels.indexOf(maxAllowed) return fixIndex <= maxIndex } isFileExcluded(filePath, excludePatterns) { const fileName = path.basename(filePath).toLowerCase() return excludePatterns.some(pattern => { const regex = new RegExp(pattern.replace('*', '.*')) return regex.test(fileName) }) } calculateLinesChanged(fix) { const originalLines = fix.original_code ? fix.original_code.split('\n').length : 0 const fixedLines = fix.fixed_code ? fix.fixed_code.split('\n').length : 0 return Math.abs(fixedLines - originalLines) + 1 } getSeverityColor(severity) { const colors = { critical: chalk.red, high: chalk.yellow, medium: chalk.blue, low: chalk.gray } return colors[severity] || chalk.gray } } /** * Approval Policy Templates for different security postures */ class ApprovalPolicyTemplates { static getTemplate(templateName) { const templates = { conservative: { automatic: { max_risk_level: 'low', allowed_types: ['exposed_secret', 'debug_statement'], max_lines_changed: 5, exclude_files: ['*auth*', '*security*', '*admin*', '*config*'] } }, balanced: { automatic: { max_risk_level: 'medium', allowed_types: [ 'exposed_secret', 'sql_injection', 'xss_vulnerability', 'path_traversal', 'debug_statement' ], max_lines_changed: 15, exclude_files: ['*auth*', '*security*'] } }, aggressive: { automatic: { max_risk_level: 'high', allowed_types: [ 'exposed_secret', 'sql_injection', 'xss_vulnerability', 'path_traversal', 'insecure_import', 'debug_statement', 'hardcoded_password', 'weak_crypto' ], max_lines_changed: 50, exclude_files: ['*admin*'] } } } return templates[templateName] || templates.balanced } } module.exports = { ApprovalWorkflow, ApprovalPolicyTemplates } |