runbooks 0.7.9__py3-none-any.whl → 0.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. runbooks/__init__.py +1 -1
  2. runbooks/cfat/README.md +12 -1
  3. runbooks/cfat/__init__.py +1 -1
  4. runbooks/cfat/assessment/runner.py +42 -34
  5. runbooks/cfat/models.py +1 -1
  6. runbooks/common/__init__.py +152 -0
  7. runbooks/common/accuracy_validator.py +1039 -0
  8. runbooks/common/context_logger.py +440 -0
  9. runbooks/common/cross_module_integration.py +594 -0
  10. runbooks/common/enhanced_exception_handler.py +1108 -0
  11. runbooks/common/enterprise_audit_integration.py +634 -0
  12. runbooks/common/mcp_integration.py +539 -0
  13. runbooks/common/performance_monitor.py +387 -0
  14. runbooks/common/profile_utils.py +216 -0
  15. runbooks/common/rich_utils.py +171 -0
  16. runbooks/feedback/user_feedback_collector.py +440 -0
  17. runbooks/finops/README.md +339 -451
  18. runbooks/finops/__init__.py +4 -21
  19. runbooks/finops/account_resolver.py +279 -0
  20. runbooks/finops/accuracy_cross_validator.py +638 -0
  21. runbooks/finops/aws_client.py +721 -36
  22. runbooks/finops/budget_integration.py +313 -0
  23. runbooks/finops/cli.py +59 -5
  24. runbooks/finops/cost_processor.py +211 -37
  25. runbooks/finops/dashboard_router.py +900 -0
  26. runbooks/finops/dashboard_runner.py +990 -232
  27. runbooks/finops/embedded_mcp_validator.py +288 -0
  28. runbooks/finops/enhanced_dashboard_runner.py +8 -7
  29. runbooks/finops/enhanced_progress.py +327 -0
  30. runbooks/finops/enhanced_trend_visualization.py +423 -0
  31. runbooks/finops/finops_dashboard.py +29 -1880
  32. runbooks/finops/helpers.py +509 -196
  33. runbooks/finops/iam_guidance.py +400 -0
  34. runbooks/finops/markdown_exporter.py +466 -0
  35. runbooks/finops/multi_dashboard.py +1502 -0
  36. runbooks/finops/optimizer.py +15 -15
  37. runbooks/finops/profile_processor.py +2 -2
  38. runbooks/finops/runbooks.inventory.organizations_discovery.log +0 -0
  39. runbooks/finops/runbooks.security.report_generator.log +0 -0
  40. runbooks/finops/runbooks.security.run_script.log +0 -0
  41. runbooks/finops/runbooks.security.security_export.log +0 -0
  42. runbooks/finops/service_mapping.py +195 -0
  43. runbooks/finops/single_dashboard.py +710 -0
  44. runbooks/finops/tests/test_reference_images_validation.py +1 -1
  45. runbooks/inventory/README.md +12 -1
  46. runbooks/inventory/core/collector.py +157 -29
  47. runbooks/inventory/list_ec2_instances.py +9 -6
  48. runbooks/inventory/list_ssm_parameters.py +10 -10
  49. runbooks/inventory/organizations_discovery.py +210 -164
  50. runbooks/inventory/rich_inventory_display.py +74 -107
  51. runbooks/inventory/run_on_multi_accounts.py +13 -13
  52. runbooks/main.py +740 -134
  53. runbooks/metrics/dora_metrics_engine.py +711 -17
  54. runbooks/monitoring/performance_monitor.py +433 -0
  55. runbooks/operate/README.md +394 -0
  56. runbooks/operate/base.py +215 -47
  57. runbooks/operate/ec2_operations.py +7 -5
  58. runbooks/operate/privatelink_operations.py +1 -1
  59. runbooks/operate/vpc_endpoints.py +1 -1
  60. runbooks/remediation/README.md +489 -13
  61. runbooks/remediation/commons.py +8 -4
  62. runbooks/security/ENTERPRISE_SECURITY_FRAMEWORK.md +506 -0
  63. runbooks/security/README.md +12 -1
  64. runbooks/security/__init__.py +164 -33
  65. runbooks/security/compliance_automation.py +12 -10
  66. runbooks/security/compliance_automation_engine.py +1021 -0
  67. runbooks/security/enterprise_security_framework.py +931 -0
  68. runbooks/security/enterprise_security_policies.json +293 -0
  69. runbooks/security/integration_test_enterprise_security.py +879 -0
  70. runbooks/security/module_security_integrator.py +641 -0
  71. runbooks/security/report_generator.py +1 -1
  72. runbooks/security/run_script.py +4 -8
  73. runbooks/security/security_baseline_tester.py +36 -49
  74. runbooks/security/security_export.py +99 -120
  75. runbooks/sre/README.md +472 -0
  76. runbooks/sre/__init__.py +33 -0
  77. runbooks/sre/mcp_reliability_engine.py +1049 -0
  78. runbooks/sre/performance_optimization_engine.py +1032 -0
  79. runbooks/sre/reliability_monitoring_framework.py +1011 -0
  80. runbooks/validation/__init__.py +2 -2
  81. runbooks/validation/benchmark.py +154 -149
  82. runbooks/validation/cli.py +159 -147
  83. runbooks/validation/mcp_validator.py +265 -236
  84. runbooks/vpc/README.md +478 -0
  85. runbooks/vpc/__init__.py +2 -2
  86. runbooks/vpc/manager_interface.py +366 -351
  87. runbooks/vpc/networking_wrapper.py +62 -33
  88. runbooks/vpc/rich_formatters.py +22 -8
  89. {runbooks-0.7.9.dist-info → runbooks-0.9.0.dist-info}/METADATA +136 -54
  90. {runbooks-0.7.9.dist-info → runbooks-0.9.0.dist-info}/RECORD +94 -55
  91. {runbooks-0.7.9.dist-info → runbooks-0.9.0.dist-info}/entry_points.txt +1 -1
  92. runbooks/finops/cross_validation.py +0 -375
  93. {runbooks-0.7.9.dist-info → runbooks-0.9.0.dist-info}/WHEEL +0 -0
  94. {runbooks-0.7.9.dist-info → runbooks-0.9.0.dist-info}/licenses/LICENSE +0 -0
  95. {runbooks-0.7.9.dist-info → runbooks-0.9.0.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,634 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Enterprise Audit Integration Framework - Comprehensive Compliance Tracking
4
+
5
+ This module provides enterprise-grade audit integration across all CloudOps modules,
6
+ enabling comprehensive compliance tracking, regulatory reporting, and governance.
7
+
8
+ Features:
9
+ - Real-time audit trail generation across all modules
10
+ - Multi-framework compliance support (SOC2, PCI-DSS, HIPAA, AWS Well-Architected)
11
+ - Executive-ready reporting with business impact analysis
12
+ - Cross-module audit correlation and analysis
13
+ - Automated compliance validation and gap analysis
14
+
15
+ Modules Integrated:
16
+ - inventory: Resource discovery audit trails
17
+ - operate: Operational change audit trails
18
+ - security: Security findings and remediation audit trails
19
+ - cfat: Cloud foundations assessment audit trails
20
+ - vpc: Network configuration audit trails
21
+ - remediation: Security remediation audit trails
22
+ - finops: Cost optimization audit trails
23
+
24
+ Author: CloudOps Runbooks Team
25
+ Version: 0.8.0
26
+ Architecture: Phase 4 Multi-Module Integration - Enterprise Audit Framework
27
+ """
28
+
29
+ import asyncio
30
+ import time
31
+ from dataclasses import dataclass, field
32
+ from datetime import datetime, timedelta
33
+ from enum import Enum
34
+ from typing import Any, Dict, List, Optional, Tuple, Union
35
+
36
+ from runbooks.common.cross_module_integration import DataFlowType, EnterpriseCrossModuleIntegrator
37
+ from runbooks.common.mcp_integration import EnterpriseMCPIntegrator, MCPValidationResult
38
+ from runbooks.common.rich_utils import (
39
+ console,
40
+ create_panel,
41
+ create_table,
42
+ format_cost,
43
+ print_error,
44
+ print_info,
45
+ print_success,
46
+ print_warning,
47
+ )
48
+
49
+
50
+ class ComplianceFramework(Enum):
51
+ """Supported compliance frameworks."""
52
+
53
+ SOC2 = "soc2"
54
+ PCI_DSS = "pci_dss"
55
+ HIPAA = "hipaa"
56
+ AWS_WELL_ARCHITECTED = "aws_well_architected"
57
+ ISO27001 = "iso27001"
58
+ GDPR = "gdpr"
59
+ CUSTOM = "custom"
60
+
61
+
62
+ class AuditSeverity(Enum):
63
+ """Audit event severity levels."""
64
+
65
+ CRITICAL = "critical"
66
+ HIGH = "high"
67
+ MEDIUM = "medium"
68
+ LOW = "low"
69
+ INFORMATIONAL = "informational"
70
+
71
+
72
+ @dataclass
73
+ class AuditEvent:
74
+ """Individual audit event record."""
75
+
76
+ timestamp: str
77
+ module: str
78
+ event_type: str
79
+ severity: AuditSeverity
80
+ resource_id: Optional[str]
81
+ account_id: Optional[str]
82
+ region: Optional[str]
83
+ user_profile: Optional[str]
84
+ description: str
85
+ compliance_frameworks: List[ComplianceFramework] = field(default_factory=list)
86
+ metadata: Dict[str, Any] = field(default_factory=dict)
87
+ correlation_id: Optional[str] = None
88
+
89
+ def to_dict(self) -> Dict[str, Any]:
90
+ """Convert audit event to dictionary."""
91
+ return {
92
+ "timestamp": self.timestamp,
93
+ "module": self.module,
94
+ "event_type": self.event_type,
95
+ "severity": self.severity.value,
96
+ "resource_id": self.resource_id,
97
+ "account_id": self.account_id,
98
+ "region": self.region,
99
+ "user_profile": self.user_profile,
100
+ "description": self.description,
101
+ "compliance_frameworks": [f.value for f in self.compliance_frameworks],
102
+ "metadata": self.metadata,
103
+ "correlation_id": self.correlation_id,
104
+ }
105
+
106
+
107
+ @dataclass
108
+ class ComplianceReport:
109
+ """Comprehensive compliance report."""
110
+
111
+ report_timestamp: str
112
+ frameworks_assessed: List[ComplianceFramework]
113
+ total_events: int
114
+ events_by_severity: Dict[str, int]
115
+ events_by_module: Dict[str, int]
116
+ compliance_score: float
117
+ critical_findings: List[AuditEvent]
118
+ recommendations: List[str]
119
+ business_impact_analysis: Dict[str, Any] = field(default_factory=dict)
120
+ audit_trail_summary: Dict[str, Any] = field(default_factory=dict)
121
+
122
+
123
+ class EnterpriseAuditIntegrator:
124
+ """
125
+ Enterprise audit integration framework for comprehensive compliance tracking.
126
+
127
+ Provides real-time audit trail generation, compliance validation, and
128
+ executive-ready reporting across all CloudOps modules.
129
+ """
130
+
131
+ def __init__(
132
+ self, user_profile: Optional[str] = None, compliance_frameworks: Optional[List[ComplianceFramework]] = None
133
+ ):
134
+ """
135
+ Initialize enterprise audit integrator.
136
+
137
+ Args:
138
+ user_profile: User profile for audit attribution
139
+ compliance_frameworks: List of compliance frameworks to assess
140
+ """
141
+ self.user_profile = user_profile
142
+ self.compliance_frameworks = compliance_frameworks or [
143
+ ComplianceFramework.SOC2,
144
+ ComplianceFramework.AWS_WELL_ARCHITECTED,
145
+ ComplianceFramework.ISO27001,
146
+ ]
147
+
148
+ # Initialize integrators
149
+ self.mcp_integrator = EnterpriseMCPIntegrator(user_profile)
150
+ self.cross_module_integrator = EnterpriseCrossModuleIntegrator(user_profile)
151
+
152
+ # Audit storage
153
+ self.audit_events: List[AuditEvent] = []
154
+ self.compliance_history: List[ComplianceReport] = []
155
+
156
+ # Performance tracking
157
+ self.start_time = time.time()
158
+
159
+ print_info(
160
+ f"Enterprise audit integrator initialized for {len(self.compliance_frameworks)} compliance frameworks"
161
+ )
162
+
163
+ def record_audit_event(
164
+ self,
165
+ module: str,
166
+ event_type: str,
167
+ description: str,
168
+ severity: AuditSeverity = AuditSeverity.INFORMATIONAL,
169
+ resource_id: Optional[str] = None,
170
+ account_id: Optional[str] = None,
171
+ region: Optional[str] = None,
172
+ metadata: Optional[Dict[str, Any]] = None,
173
+ correlation_id: Optional[str] = None,
174
+ ) -> AuditEvent:
175
+ """
176
+ Record a new audit event.
177
+
178
+ Args:
179
+ module: Source module name
180
+ event_type: Type of audit event
181
+ description: Human-readable description
182
+ severity: Event severity level
183
+ resource_id: Associated AWS resource ID
184
+ account_id: AWS account ID
185
+ region: AWS region
186
+ metadata: Additional metadata
187
+ correlation_id: Correlation ID for related events
188
+
189
+ Returns:
190
+ Created audit event
191
+ """
192
+ # Determine applicable compliance frameworks
193
+ applicable_frameworks = self._determine_applicable_frameworks(event_type, module)
194
+
195
+ audit_event = AuditEvent(
196
+ timestamp=datetime.now().isoformat(),
197
+ module=module,
198
+ event_type=event_type,
199
+ severity=severity,
200
+ resource_id=resource_id,
201
+ account_id=account_id,
202
+ region=region,
203
+ user_profile=self.user_profile,
204
+ description=description,
205
+ compliance_frameworks=applicable_frameworks,
206
+ metadata=metadata or {},
207
+ correlation_id=correlation_id,
208
+ )
209
+
210
+ self.audit_events.append(audit_event)
211
+
212
+ # Log critical events immediately
213
+ if severity in [AuditSeverity.CRITICAL, AuditSeverity.HIGH]:
214
+ print_warning(f"🚨 {severity.value.upper()} audit event: {description}")
215
+
216
+ return audit_event
217
+
218
+ async def generate_comprehensive_compliance_report(
219
+ self, time_period_days: int = 30, include_business_impact: bool = True
220
+ ) -> ComplianceReport:
221
+ """
222
+ Generate comprehensive compliance report across all modules.
223
+
224
+ Args:
225
+ time_period_days: Number of days to include in report
226
+ include_business_impact: Whether to include business impact analysis
227
+
228
+ Returns:
229
+ Comprehensive compliance report
230
+ """
231
+ print_info(f"Generating comprehensive compliance report for {time_period_days} days")
232
+
233
+ # Filter events by time period
234
+ cutoff_date = datetime.now() - timedelta(days=time_period_days)
235
+ recent_events = [event for event in self.audit_events if datetime.fromisoformat(event.timestamp) >= cutoff_date]
236
+
237
+ # Analyze events by severity
238
+ events_by_severity = {}
239
+ for severity in AuditSeverity:
240
+ events_by_severity[severity.value] = len([e for e in recent_events if e.severity == severity])
241
+
242
+ # Analyze events by module
243
+ events_by_module = {}
244
+ for event in recent_events:
245
+ events_by_module[event.module] = events_by_module.get(event.module, 0) + 1
246
+
247
+ # Calculate compliance score
248
+ compliance_score = self._calculate_compliance_score(recent_events)
249
+
250
+ # Identify critical findings
251
+ critical_findings = [
252
+ event for event in recent_events if event.severity in [AuditSeverity.CRITICAL, AuditSeverity.HIGH]
253
+ ]
254
+
255
+ # Generate recommendations
256
+ recommendations = self._generate_compliance_recommendations(recent_events, critical_findings)
257
+
258
+ # Business impact analysis
259
+ business_impact = {}
260
+ if include_business_impact:
261
+ business_impact = await self._analyze_business_impact(recent_events)
262
+
263
+ # Create compliance report
264
+ report = ComplianceReport(
265
+ report_timestamp=datetime.now().isoformat(),
266
+ frameworks_assessed=self.compliance_frameworks,
267
+ total_events=len(recent_events),
268
+ events_by_severity=events_by_severity,
269
+ events_by_module=events_by_module,
270
+ compliance_score=compliance_score,
271
+ critical_findings=critical_findings,
272
+ recommendations=recommendations,
273
+ business_impact_analysis=business_impact,
274
+ audit_trail_summary=self._generate_audit_trail_summary(recent_events),
275
+ )
276
+
277
+ # Store in history
278
+ self.compliance_history.append(report)
279
+
280
+ print_success(
281
+ f"Compliance report generated: {compliance_score:.1f}% compliance score with {len(critical_findings)} critical findings"
282
+ )
283
+
284
+ return report
285
+
286
+ async def audit_inventory_operations(self, inventory_results: Dict[str, Any]) -> List[AuditEvent]:
287
+ """
288
+ Generate audit events for inventory operations.
289
+
290
+ Args:
291
+ inventory_results: Results from inventory collection
292
+
293
+ Returns:
294
+ List of generated audit events
295
+ """
296
+ audit_events = []
297
+
298
+ # Record inventory discovery event
299
+ total_resources = inventory_results.get("summary", {}).get("total_resources", 0)
300
+ accounts_scanned = len(inventory_results.get("metadata", {}).get("account_ids", []))
301
+
302
+ audit_event = self.record_audit_event(
303
+ module="inventory",
304
+ event_type="resource_discovery",
305
+ description=f"Discovered {total_resources} resources across {accounts_scanned} accounts",
306
+ severity=AuditSeverity.INFORMATIONAL,
307
+ metadata={
308
+ "total_resources": total_resources,
309
+ "accounts_scanned": accounts_scanned,
310
+ "resource_types": inventory_results.get("metadata", {}).get("resource_types", []),
311
+ },
312
+ )
313
+ audit_events.append(audit_event)
314
+
315
+ # Audit resource compliance
316
+ compliance_issues = self._identify_inventory_compliance_issues(inventory_results)
317
+ for issue in compliance_issues:
318
+ audit_event = self.record_audit_event(
319
+ module="inventory",
320
+ event_type="compliance_issue",
321
+ description=issue["description"],
322
+ severity=AuditSeverity.HIGH if issue["critical"] else AuditSeverity.MEDIUM,
323
+ resource_id=issue.get("resource_id"),
324
+ account_id=issue.get("account_id"),
325
+ metadata=issue.get("metadata", {}),
326
+ )
327
+ audit_events.append(audit_event)
328
+
329
+ return audit_events
330
+
331
+ async def audit_security_operations(self, security_results: Dict[str, Any]) -> List[AuditEvent]:
332
+ """
333
+ Generate audit events for security operations.
334
+
335
+ Args:
336
+ security_results: Results from security assessment
337
+
338
+ Returns:
339
+ List of generated audit events
340
+ """
341
+ audit_events = []
342
+
343
+ # Record security assessment event
344
+ findings = security_results.get("findings", [])
345
+ critical_findings = [f for f in findings if f.get("severity") == "CRITICAL"]
346
+
347
+ audit_event = self.record_audit_event(
348
+ module="security",
349
+ event_type="security_assessment",
350
+ description=f"Security assessment completed with {len(findings)} findings ({len(critical_findings)} critical)",
351
+ severity=AuditSeverity.CRITICAL if critical_findings else AuditSeverity.INFORMATIONAL,
352
+ metadata={
353
+ "total_findings": len(findings),
354
+ "critical_findings": len(critical_findings),
355
+ "assessment_timestamp": datetime.now().isoformat(),
356
+ },
357
+ )
358
+ audit_events.append(audit_event)
359
+
360
+ # Record individual critical findings
361
+ for finding in critical_findings:
362
+ audit_event = self.record_audit_event(
363
+ module="security",
364
+ event_type="critical_security_finding",
365
+ description=finding.get("description", "Critical security finding identified"),
366
+ severity=AuditSeverity.CRITICAL,
367
+ resource_id=finding.get("resource_id"),
368
+ account_id=finding.get("account_id"),
369
+ metadata=finding,
370
+ )
371
+ audit_events.append(audit_event)
372
+
373
+ return audit_events
374
+
375
+ async def audit_operate_operations(self, operation_results: List[Dict[str, Any]]) -> List[AuditEvent]:
376
+ """
377
+ Generate audit events for operational activities.
378
+
379
+ Args:
380
+ operation_results: Results from operate module
381
+
382
+ Returns:
383
+ List of generated audit events
384
+ """
385
+ audit_events = []
386
+
387
+ for operation in operation_results:
388
+ # Determine severity based on operation type and outcome
389
+ severity = (
390
+ AuditSeverity.HIGH if operation.get("type") in ["terminate", "delete"] else AuditSeverity.INFORMATIONAL
391
+ )
392
+ if not operation.get("success", True):
393
+ severity = AuditSeverity.HIGH
394
+
395
+ audit_event = self.record_audit_event(
396
+ module="operate",
397
+ event_type=f"operation_{operation.get('type', 'unknown')}",
398
+ description=f"Operation {operation.get('type', 'unknown')} on {operation.get('resource_id', 'unknown')} {'succeeded' if operation.get('success') else 'failed'}",
399
+ severity=severity,
400
+ resource_id=operation.get("resource_id"),
401
+ account_id=operation.get("account_id"),
402
+ region=operation.get("region"),
403
+ metadata=operation,
404
+ )
405
+ audit_events.append(audit_event)
406
+
407
+ return audit_events
408
+
409
+ def _determine_applicable_frameworks(self, event_type: str, module: str) -> List[ComplianceFramework]:
410
+ """Determine which compliance frameworks apply to an event."""
411
+ applicable = []
412
+
413
+ # All events apply to SOC2 and ISO27001 for general security controls
414
+ if ComplianceFramework.SOC2 in self.compliance_frameworks:
415
+ applicable.append(ComplianceFramework.SOC2)
416
+ if ComplianceFramework.ISO27001 in self.compliance_frameworks:
417
+ applicable.append(ComplianceFramework.ISO27001)
418
+
419
+ # AWS Well-Architected applies to all AWS operations
420
+ if ComplianceFramework.AWS_WELL_ARCHITECTED in self.compliance_frameworks:
421
+ applicable.append(ComplianceFramework.AWS_WELL_ARCHITECTED)
422
+
423
+ # Security and data handling events may apply to PCI-DSS and HIPAA
424
+ if event_type in ["security_assessment", "data_access", "encryption_change"]:
425
+ if ComplianceFramework.PCI_DSS in self.compliance_frameworks:
426
+ applicable.append(ComplianceFramework.PCI_DSS)
427
+ if ComplianceFramework.HIPAA in self.compliance_frameworks:
428
+ applicable.append(ComplianceFramework.HIPAA)
429
+
430
+ return applicable
431
+
432
+ def _calculate_compliance_score(self, events: List[AuditEvent]) -> float:
433
+ """Calculate overall compliance score based on audit events."""
434
+ if not events:
435
+ return 100.0
436
+
437
+ # Weight events by severity
438
+ severity_weights = {
439
+ AuditSeverity.CRITICAL: -10,
440
+ AuditSeverity.HIGH: -5,
441
+ AuditSeverity.MEDIUM: -2,
442
+ AuditSeverity.LOW: -1,
443
+ AuditSeverity.INFORMATIONAL: 0,
444
+ }
445
+
446
+ total_impact = sum(severity_weights.get(event.severity, 0) for event in events)
447
+
448
+ # Calculate score (100 is perfect, penalties reduce score)
449
+ base_score = 100.0
450
+ penalty = abs(total_impact) / len(events) * 10 # Scale penalty
451
+
452
+ compliance_score = max(0.0, base_score - penalty)
453
+ return min(100.0, compliance_score)
454
+
455
+ def _generate_compliance_recommendations(
456
+ self, events: List[AuditEvent], critical_findings: List[AuditEvent]
457
+ ) -> List[str]:
458
+ """Generate compliance recommendations based on audit events."""
459
+ recommendations = []
460
+
461
+ if critical_findings:
462
+ recommendations.append(f"Address {len(critical_findings)} critical security findings immediately")
463
+
464
+ # Analyze event patterns
465
+ module_event_counts = {}
466
+ for event in events:
467
+ if event.severity in [AuditSeverity.CRITICAL, AuditSeverity.HIGH]:
468
+ module_event_counts[event.module] = module_event_counts.get(event.module, 0) + 1
469
+
470
+ # Recommend focus areas
471
+ if module_event_counts:
472
+ top_module = max(module_event_counts, key=module_event_counts.get)
473
+ recommendations.append(
474
+ f"Focus security improvements on {top_module} module ({module_event_counts[top_module]} high-priority events)"
475
+ )
476
+
477
+ # Generic recommendations
478
+ recommendations.extend(
479
+ [
480
+ "Implement automated security remediation for common findings",
481
+ "Establish regular compliance monitoring and reporting",
482
+ "Enhance access controls and monitoring for critical operations",
483
+ "Review and update security policies based on audit findings",
484
+ ]
485
+ )
486
+
487
+ return recommendations
488
+
489
+ async def _analyze_business_impact(self, events: List[AuditEvent]) -> Dict[str, Any]:
490
+ """Analyze business impact of audit events."""
491
+ # Estimate potential cost impact
492
+ critical_events = [e for e in events if e.severity == AuditSeverity.CRITICAL]
493
+ high_events = [e for e in events if e.severity == AuditSeverity.HIGH]
494
+
495
+ # Rough cost estimates for different types of findings
496
+ estimated_cost_impact = len(critical_events) * 10000 + len(high_events) * 2500
497
+
498
+ return {
499
+ "estimated_cost_impact_usd": estimated_cost_impact,
500
+ "critical_business_risks": len(critical_events),
501
+ "compliance_violations": len([e for e in events if "compliance" in e.event_type]),
502
+ "operational_disruptions": len(
503
+ [e for e in events if e.module == "operate" and not e.metadata.get("success", True)]
504
+ ),
505
+ "security_exposure_level": "HIGH" if critical_events else "MEDIUM" if high_events else "LOW",
506
+ }
507
+
508
+ def _generate_audit_trail_summary(self, events: List[AuditEvent]) -> Dict[str, Any]:
509
+ """Generate audit trail summary statistics."""
510
+ return {
511
+ "total_events": len(events),
512
+ "unique_resources": len(set(e.resource_id for e in events if e.resource_id)),
513
+ "unique_accounts": len(set(e.account_id for e in events if e.account_id)),
514
+ "event_types": list(set(e.event_type for e in events)),
515
+ "time_span_days": (
516
+ datetime.fromisoformat(max(e.timestamp for e in events))
517
+ - datetime.fromisoformat(min(e.timestamp for e in events))
518
+ ).days
519
+ if events
520
+ else 0,
521
+ }
522
+
523
+ def _identify_inventory_compliance_issues(self, inventory_results: Dict[str, Any]) -> List[Dict[str, Any]]:
524
+ """Identify compliance issues from inventory results."""
525
+ issues = []
526
+
527
+ # Example compliance checks
528
+ resources = inventory_results.get("resources", {})
529
+
530
+ # Check for untagged resources
531
+ for resource_type, accounts_data in resources.items():
532
+ for account_id, account_data in accounts_data.items():
533
+ if resource_type == "ec2" and "instances" in account_data:
534
+ for instance in account_data["instances"]:
535
+ if not instance.get("tags"):
536
+ issues.append(
537
+ {
538
+ "description": f"Untagged EC2 instance {instance.get('instance_id')}",
539
+ "resource_id": instance.get("instance_id"),
540
+ "account_id": account_id,
541
+ "critical": False,
542
+ "metadata": {"compliance_rule": "required_tagging"},
543
+ }
544
+ )
545
+
546
+ return issues
547
+
548
+ def display_compliance_dashboard(self, report: ComplianceReport) -> None:
549
+ """Display comprehensive compliance dashboard using Rich formatting."""
550
+
551
+ # Main compliance score panel
552
+ score_color = "green" if report.compliance_score >= 95 else "yellow" if report.compliance_score >= 80 else "red"
553
+ score_panel = create_panel(
554
+ f"[{score_color}]{report.compliance_score:.1f}%[/{score_color}]", title="Overall Compliance Score"
555
+ )
556
+ console.print(score_panel)
557
+
558
+ # Events by severity table
559
+ severity_table = create_table(
560
+ title="Events by Severity", columns=[("Severity", "cyan"), ("Count", "magenta"), ("Percentage", "green")]
561
+ )
562
+
563
+ total_events = report.total_events
564
+ for severity, count in report.events_by_severity.items():
565
+ percentage = (count / total_events * 100) if total_events > 0 else 0
566
+ severity_table.add_row(severity.upper(), str(count), f"{percentage:.1f}%")
567
+
568
+ console.print(severity_table)
569
+
570
+ # Critical findings summary
571
+ if report.critical_findings:
572
+ console.print(
573
+ f"\n[red]🚨 {len(report.critical_findings)} Critical Findings Requiring Immediate Attention:[/red]"
574
+ )
575
+ for finding in report.critical_findings[:5]: # Show top 5
576
+ console.print(f" • {finding.description}")
577
+ if len(report.critical_findings) > 5:
578
+ console.print(f" • ... and {len(report.critical_findings) - 5} more")
579
+
580
+ # Business impact
581
+ if report.business_impact_analysis:
582
+ impact = report.business_impact_analysis
583
+ cost_impact = impact.get("estimated_cost_impact_usd", 0)
584
+
585
+ if cost_impact > 0:
586
+ impact_panel = create_panel(
587
+ f"Estimated Cost Impact: {format_cost(cost_impact)}\n"
588
+ f"Security Exposure: {impact.get('security_exposure_level', 'UNKNOWN')}\n"
589
+ f"Compliance Violations: {impact.get('compliance_violations', 0)}",
590
+ title="Business Impact Analysis",
591
+ )
592
+ console.print(impact_panel)
593
+
594
+ # Recommendations
595
+ if report.recommendations:
596
+ console.print(f"\n[cyan]📋 Top Recommendations:[/cyan]")
597
+ for i, rec in enumerate(report.recommendations[:3], 1):
598
+ console.print(f" {i}. {rec}")
599
+
600
+ def export_audit_report(self, report: ComplianceReport, format: str = "json") -> str:
601
+ """Export compliance report in specified format."""
602
+ if format.lower() == "json":
603
+ import json
604
+
605
+ return json.dumps(
606
+ {
607
+ "compliance_report": {
608
+ "report_timestamp": report.report_timestamp,
609
+ "frameworks_assessed": [f.value for f in report.frameworks_assessed],
610
+ "compliance_score": report.compliance_score,
611
+ "total_events": report.total_events,
612
+ "events_by_severity": report.events_by_severity,
613
+ "events_by_module": report.events_by_module,
614
+ "critical_findings": [finding.to_dict() for finding in report.critical_findings],
615
+ "recommendations": report.recommendations,
616
+ "business_impact_analysis": report.business_impact_analysis,
617
+ "audit_trail_summary": report.audit_trail_summary,
618
+ }
619
+ },
620
+ indent=2,
621
+ )
622
+
623
+ # Add other formats as needed (CSV, PDF, etc.)
624
+ return str(report)
625
+
626
+
627
+ # Export public interface
628
+ __all__ = [
629
+ "EnterpriseAuditIntegrator",
630
+ "ComplianceFramework",
631
+ "AuditSeverity",
632
+ "AuditEvent",
633
+ "ComplianceReport",
634
+ ]