python
import streamlit as st
import yaml
import json
import deepdiff
from datetime import datetime, timedelta
from typing import Dict, Any, List, Tuple
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import hashlib
from dataclasses import dataclass
from enum import Enum
import sqlite3
import os
# ========================================
# ARCHITECTURE OVERVIEW
# ========================================
# This is a fully functional cross-environment config diff visualizer built with Streamlit.
# Key Features:
# 1. **Cross-Environment Support**: Compares configs from multiple envs (e.g., dev/staging/prod).
# - Supports YAML, JSON, or directories of files.
# 2. **Normalization**: Canonicalizes configs (sort keys, normalize strings/case, handle lists as sets).
# 3. **Diff Visualization**: Interactive tree view, side-by-side tables, risk heatmap.
# 4. **Policy Checks**:
# - **Risk Scoring**: Rule-based scoring (e.g., security=high, perf=med, cosmetic=low).
# - **Approval Routing**: Workflow with approvers, states (pending/approved/rejected).
# - **SLA Tracking**: Monitors review/approval times vs. SLAs (e.g., P1: 1hr, P2: 4hr).
# 5. **Persistence**: SQLite for diffs, approvals, SLA history.
# 6. **Extensibility**: Plugin rules for risk/approval.
#
# Tech Stack: Streamlit (UI), DeepDiff (diffing), Plotly (viz), SQLite (state).
# Run: `pip install streamlit deepdiff pyyaml plotly pandas ruamel.yaml` then `streamlit run app.py`
# ========================================
# Data Classes
@dataclass
class DiffItem:
path: str
old_value: Any
new_value: Any
change_type: str # added/removed/changed/type_change
risk_score: int = 0
risk_category: str = "low"
@dataclass
class Approval:
diff_id: str
approver: str
state: str # pending/approved/rejected
timestamp: datetime
sla_status: str # on_track/breached
class RiskCategory(Enum):
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
CRITICAL = "critical"
# Global DB Setup
DB_PATH = "config_diff.db"
@st.cache_resource
def init_db():
conn = sqlite3.connect(DB_PATH)
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS diffs
(id TEXT PRIMARY KEY, env_a TEXT, env_b TEXT, diff_data TEXT, created_at TIMESTAMP)''')
c.execute('''CREATE TABLE IF NOT EXISTS approvals
(diff_id TEXT, approver TEXT, state TEXT, timestamp TIMESTAMP, sla_status TEXT,
FOREIGN KEY(diff_id) REFERENCES diffs (id))''')
conn.commit()
return conn
conn = init_db()
# Normalization Function
def normalize_config(config: Dict[str, Any]) -> Dict[str, Any]:
"""Normalize dict: sort keys recursively, lowercase strings, sort lists, handle None."""
if isinstance(config, dict):
return {k.lower(): normalize_config(v) for k, v in sorted(config.items())}
elif isinstance(config, list):
# Treat as set for diffing, but preserve list
return sorted(normalize_config(item) for item in config)
elif isinstance(config, str):
return config.lower().strip()
elif config is None:
return "null"
return config
# Config Loader
def load_config(file_content: str, file_path: str = "") -> Dict[str, Any]:
"""Load YAML/JSON from string or file."""
if file_path.endswith('.yaml') or file_path.endswith('.yml'):
return yaml.safe_load(file_content)
else:
return json.loads(file_content)
# Risk Scoring Rules (Extensible)
RISK_RULES = {
"security": {"keywords": ["password", "key", "secret", "auth", "ssl"], "score": 4, "cat": "critical"},
"database": {"keywords": ["db", "sql", "mongo"], "score": 3, "cat": "high"},
"performance": {"keywords": ["cpu", "memory", "timeout"], "score": 2, "cat": "medium"},
"cosmetic": {"keywords": ["comment", "label"], "score": 1, "cat": "low"}
}
def score_risk(path: str, old_val: Any, new_val: Any) -> Tuple[int, str]:
"""Score risk based on path and value changes."""
path_lower = path.lower()
max_score = 0
max_cat = "low"
for category, rule in RISK_RULES.items():
if any(kw in path_lower for kw in rule["keywords"]):
score = rule["score"]
if score > max_score:
max_score = score
max_cat = rule["cat"]
# Value-based boosts
if isinstance(old_val, str) and "disable" in old_val.lower() and "enable" in str(new_val).lower():
max_score += 1
return max_score, max_cat
# Diff Engine
def compute_diff(env_a_config: Dict, env_b_config: Dict) -> List[DiffItem]:
"""Compute normalized deep diff."""
norm_a = normalize_config(env_a_config)
norm_b = normalize_config(env_b_config)
ddiff = deepdiff.DeepDiff(norm_a, norm_b, ignore_order=True, report_repetition=False)
diffs = []
if 'dictionary_item_added' in ddiff:
for path, val in ddiff['dictionary_item_added'].items():
diffs.append(DiffItem(path=str(path), old_value=None, new_value=val, change_type='added',
**score_risk(str(path), None, val)))
if 'dictionary_item_removed' in ddiff:
for path, val in ddiff['dictionary_item_removed'].items():
diffs.append(DiffItem(path=str(path), old_value=val, new_value=None, change_type='removed',
**score_risk(str(path), val, None)))
if 'values_changed' in ddiff:
for path, change in ddiff['values_changed'].items():
diffs.append(DiffItem(path=str(path), old_value=change.t1, new_value=change.t2, change_type='changed',
**score_risk(str(path), change.t1, change.t2)))
if 'type_changes' in ddiff:
for path, change in ddiff['type_changes'].items():
diffs.append(DiffItem(path=str(path), old_value=change.t1, new_value=change.t2, change_type='type_change',
**score_risk(str(path), change.t1, change.t2)))
return sorted(diffs, key=lambda d: (-d.risk_score, d.path))
# SLA Calculation
SLA_THRESHOLDS = {1: timedelta(hours=1), 2: timedelta(hours=4), 3: timedelta(hours=24), 4: timedelta(days=7)}
def check_sla(diff_id: str, now: datetime = None) -> str:
if now is None: now = datetime.now()
c = conn.cursor()
c.execute("SELECT MAX(timestamp) FROM approvals WHERE diff_id=? AND state='approved'", (diff_id,))
latest = c.fetchone()[0]
if latest:
delta = now - datetime.fromisoformat(latest)
# Find max risk for diff
c.execute("SELECT MAX(risk_score) FROM diffs WHERE id=?", (diff_id,))
max_risk = c.fetchone()[0] or 0
threshold = SLA_THRESHOLDS.get(max_risk, timedelta(days=1))
return "on_track" if delta <= threshold else "breached"
return "pending"
# Streamlit UI
st.set_page_config(page_title="Config Diff Visualizer", layout="wide")
st.title("🚀 Cross-Environment Config Diff Visualizer")
st.markdown("**With Policy Checks: Normalization, Risk Scoring, Approval Routing & SLA Tracking**")
# Sidebar: Inputs
st.sidebar.header("Environments")
env_a_file = st.sidebar.file_uploader("Env A Config (YAML/JSON)", key="env_a")
env_b_file = st.sidebar.file_uploader("Env B Config (YAML/JSON)", key="env_b")
env_a_name = st.sidebar.text_input("Env A Name", "Dev")
env_b_name = st.sidebar.text_input("Env B Name", "Prod")
if st.sidebar.button("Compute Diff") and env_a_file and env_b_file:
# Load and process
config_a = load_config(env_a_file.read().decode(), env_a_file.name)
config_b = load_config(env_b_file.read().decode(), env_b_file.name)
diffs = compute_diff(config_a, config_b)
# Persist diff
diff_id = hashlib.md5(f"{env_a_name}:{env_b_name}:{str(diffs)}".encode()).hexdigest()
conn.execute("INSERT OR REPLACE INTO diffs (id, env_a, env_b, diff_data, created_at) VALUES (?, ?, ?, ?, ?)",
(diff_id, env_a_name, env_b_name, str(diffs), datetime.now()))
conn.commit()
st.session_state['diffs'] = diffs
st.session_state['diff_id'] = diff_id
st.session_state['env_a_name'] = env_a_name
st.session_state['env_b_name'] = env_b_name
st.rerun()
# Main Content
if 'diffs' in st.session_state:
diffs = st.session_state['diffs']
diff_id = st.session_state['diff_id']
env_a_name = st.session_state.get('env_a_name', 'Env A')
env_b_name = st.session_state.get('env_b_name', 'Env B')
st.header(f"Diff: {env_a_name} vs {env_b_name}")
# Risk Summary Metrics
col1, col2, col3, col4 = st.columns(4)
risk_counts = pd.DataFrame(diffs).groupby('risk_category').size().to_dict()
with col1:
st.metric("Total Diffs", len(diffs))
with col2:
st.metric("High/Crit Risks", risk_counts.get('high', 0) + risk_counts.get('critical', 0))
with col3:
st.metric("Avg Risk Score", round(pd.DataFrame(diffs)['risk_score'].mean(), 1))
with col4:
sla = check_sla(diff_id)
st.metric("SLA Status", sla, delta="breached" if sla == "breached" else None)
# Risk Heatmap
fig = go.Figure(data=go.Scatter(
x=[d.path for d in diffs],
y=[d.risk_score for d in diffs],
mode='markers',
marker=dict(size=10, color=[d.risk_score for d in diffs], colorscale='Reds', showscale=True)
))
fig.update_layout(height=400, xaxis_tickangle=45)
st.plotly_chart(fig, use_container_width=True)
# Diff Table
df = pd.DataFrame([
{
'Path': d.path,
'Change Type': d.change_type,
f'{env_a_name}': d.old_value,
f'{env_b_name}': d.new_value,
'Risk Score': d.risk_score,
'Risk Category': d.risk_category,
'Actions': f"🔄"
}
for d in diffs
])
st.dataframe(df, use_container_width=True, hide_index=True)
# Approval Routing
st.subheader("Approval Workflow")
approvals = pd.read_sql(f"SELECT * FROM approvals WHERE diff_id='{diff_id}' ORDER BY timestamp", conn)
st.dataframe(approvals, use_container_width=True)
approver = st.selectbox("Approver", ["devops-lead", "security-team", "prod-owner"])
col_app1, col_app2 = st.columns(2)
with col_app1:
if st.button("✅ Approve"):
now = datetime.now()
sla_status = check_sla(diff_id, now)
conn.execute("INSERT INTO approvals VALUES (?, ?, 'approved', ?, ?)", (diff_id, approver, now.isoformat(), sla_status))
conn.commit()
st.rerun()
with col_app2:
if st.button("❌ Reject"):
now = datetime.now()
conn.execute("INSERT INTO approvals VALUES (?, ?, 'rejected', ?, 'n/a')", (diff_id, approver, now.isoformat()))
conn.commit()
st.rerun()
# History & SLA Trends
st.subheader("SLA History")
if not approvals.empty:
fig_hist = make_subplots(specs=[[{"secondary_y": True}]])
# Add more viz as needed
st.plotly_chart(fig_hist)
# Raw Diff JSON
with st.expander("View Raw Normalized Diffs"):
st.json(diffs)
# Footer
st.markdown("---")
st.markdown("*Built by Sherlock (Trailblazer Labs). Extensible for custom rules/DB integrations.*")