Building Compliance Dashboards
Building Compliance Dashboards
Create comprehensive dashboards for compliance visibility:
# compliance-dashboard-generator.py
import json
from datetime import datetime, timedelta
import plotly.graph_objects as go
import plotly.express as px
from plotly.subplots import make_subplots
import pandas as pd
class ComplianceDashboard:
def __init__(self, scan_data_path: str):
self.scan_data = self.load_scan_data(scan_data_path)
self.metrics = self.calculate_metrics()
def load_scan_data(self, path: str) -> List[Dict]:
"""Load historical scan data"""
# In production, this would query a database
with open(path, 'r') as f:
return json.load(f)
def calculate_metrics(self) -> Dict:
"""Calculate compliance metrics"""
metrics = {
'current_compliance_score': 0,
'trend_data': [],
'framework_scores': {},
'vulnerability_trends': {},
'top_violations': []
}
# Calculate current compliance score
compliant_images = sum(
1 for scan in self.scan_data
if all(framework['compliant']
for framework in scan['compliance_status'].values())
)
total_images = len(self.scan_data)
metrics['current_compliance_score'] = compliant_images / total_images if total_images > 0 else 0
# Calculate per-framework scores
for framework in ['pci_dss', 'hipaa', 'soc2']:
compliant = sum(
1 for scan in self.scan_data
if scan['compliance_status'].get(framework, {}).get('compliant', False)
)
metrics['framework_scores'][framework] = compliant / total_images if total_images > 0 else 0
return metrics
def generate_compliance_scorecard(self) -> go.Figure:
"""Generate compliance scorecard visualization"""
fig = make_subplots(
rows=2, cols=2,
subplot_titles=('Overall Compliance Score', 'Framework Compliance',
'Vulnerability Distribution', 'Compliance Trend'),
specs=[[{'type': 'indicator'}, {'type': 'bar'}],
[{'type': 'pie'}, {'type': 'scatter'}]]
)
# Overall compliance score gauge
fig.add_trace(
go.Indicator(
mode="gauge+number+delta",
value=self.metrics['current_compliance_score'] * 100,
domain={'x': [0, 1], 'y': [0, 1]},
title={'text': "Compliance %"},
delta={'reference': 95},
gauge={
'axis': {'range': [None, 100]},
'bar': {'color': "darkblue"},
'steps': [
{'range': [0, 80], 'color': "lightgray"},
{'range': [80, 95], 'color': "gray"}
],
'threshold': {
'line': {'color': "red", 'width': 4},
'thickness': 0.75,
'value': 95
}
}
),
row=1, col=1
)
# Framework compliance bars
frameworks = list(self.metrics['framework_scores'].keys())
scores = [score * 100 for score in self.metrics['framework_scores'].values()]
fig.add_trace(
go.Bar(
x=frameworks,
y=scores,
text=[f"{score:.1f}%" for score in scores],
textposition='auto',
marker_color=['green' if score >= 95 else 'orange' if score >= 80 else 'red'
for score in scores]
),
row=1, col=2
)
# Vulnerability distribution pie chart
vuln_counts = self.aggregate_vulnerabilities()
fig.add_trace(
go.Pie(
labels=list(vuln_counts.keys()),
values=list(vuln_counts.values()),
hole=.3,
marker_colors=['#d62728', '#ff7f0e', '#ffbb78', '#98df8a']
),
row=2, col=1
)
# Compliance trend line
trend_data = self.calculate_trend_data()
fig.add_trace(
go.Scatter(
x=trend_data['dates'],
y=trend_data['scores'],
mode='lines+markers',
name='Compliance Score',
line=dict(color='blue', width=2)
),
row=2, col=2
)
# Add threshold line
fig.add_hline(
y=95,
line_dash="dash",
line_color="red",
annotation_text="Target: 95%",
row=2, col=2
)
fig.update_layout(
title_text="Container Security Compliance Dashboard",
showlegend=False,
height=800
)
return fig
def generate_detailed_report(self) -> str:
"""Generate detailed compliance report"""
report = f"""
# Container Security Compliance Report
Generated: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}