import json
import hashlib
import logging
from dataclasses import dataclass
from typing import List, Dict, Any, Optional
from enum import Enum
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# --- Enums and Data Structures ---
class DriftAction(Enum):
NONE = 0
ALERT = 1
ROLLBACK = 2
@dataclass
class DriftReport:
is_drifted: bool
details: str
expected_hash: str
actual_hash: str
# --- 1. CDN Client (Mock Interface) ---
class CDNClient:
"""
Simulates interaction with a CDN provider API (e.g., Cloudflare, Fastly).
In a real scenario, this would use `requests` or provider SDKs.
"""
def __init__(self):
self._store = {} # Simulated edge storage
def fetch_live_config(self, edge_id: str) -> Dict:
"""Retrieves the currently active config from the Edge."""
logger.info(f"Fetching live config for Edge ID: {edge_id}")
return self._store.get(edge_id, {})
def push_config(self, edge_id: str, config: Dict) -> bool:
"""Pushes a new config (used for Rollback/Remediation)."""
logger.info(f"Pushing config to Edge ID: {edge_id}")
self._store[edge_id] = config
return True
# --- 2. Core Logic: Normalizer & Parity Checker ---
class ConfigNormalizer:
"""
Ensures 'Rule Parity' by standardizing configs before comparison.
Removes ephemeral metadata (timestamps, IDs) that differ between systems.
"""
@staticmethod
def sort_lists_recursive(obj: Any) -> Any:
"""
Recursively sorts lists of dictionaries by a unique key (if available)
or string representation to ensure order doesn't cause false drift.
"""
if isinstance(obj, dict):
return {k: ConfigNormalizer.sort_lists_recursive(v) for k, v in sorted(obj.items())}
elif isinstance(obj, list):
# Sort list of dicts by 'rule_id' or 'name' if present, else sort by json string
if all(isinstance(x, dict) for x in obj):
if all('rule_id' in x for x in obj):
return sorted([ConfigNormalizer.sort_lists_recursive(x) for x in obj], key=lambda x: x['rule_id'])
elif all('name' in x for x in obj):
return sorted([ConfigNormalizer.sort_lists_recursive(x) for x in obj], key=lambda x: x['name'])
return sorted([ConfigNormalizer.sort_lists_recursive(x) for x in obj], key=lambda x: str(x))
else:
return obj
@staticmethod
def remove_metadata(obj: Dict) -> Dict:
"""Strips fields that change automatically on the CDN side."""
keys_to_remove = ['last_updated', 'etag', 'version', 'internal_id', 'created_at']
return {k: v for k, v in obj.items() if k not in keys_to_remove}
@staticmethod
def get_canonical_hash(config: Dict) -> str:
"""Generates a deterministic hash of the config logic."""
cleaned = ConfigNormalizer.remove_metadata(config)
sorted_obj = ConfigNormalizer.sort_lists_recursive(cleaned)
# deterministic json string
json_str = json.dumps(sorted_obj, separators=(',', ':'), sort_keys=True)
return hashlib.sha256(json_str.encode('utf-8')).hexdigest()
class DriftDetector:
def __init__(self, cdn_client: CDNClient):
self.cdn = cdn_client
def check_parity(self, edge_id: str, source_of_truth: Dict) -> DriftReport:
"""
Compares the Source of Truth (Git) vs Live Config (CDN).
"""
live_config = self.cdn.fetch_live_config(edge_id)
expected_hash = ConfigNormalizer.get_canonical_hash(source_of_truth)
actual_hash = ConfigNormalizer.get_canonical_hash(live_config)
if expected_hash == actual_hash:
return DriftReport(False, "Configurations match.", expected_hash, actual_hash)
else:
# Find specific differences for the report
diffs = self._find_diff(source_of_truth, live_config)
return DriftReport(True, diffs, expected_hash, actual_hash)
def _find_diff(self, expected: Dict, actual: Dict) -> str:
# Simple diff logic for demo; in prod use `deepdiff` library
expected_rules = {r['rule_id']: r for r in expected.get('rules', [])}
actual_rules = {r['rule_id']: r for r in actual.get('rules', [])}
missing = set(expected_rules.keys()) - set(actual_rules.keys())
extra = set(actual_rules.keys()) - set(expected_rules.keys())
msg = []
if missing: msg.append(f"Missing rules: {missing}")
if extra: msg.append(f"Unauthorized rules added: {extra}")
if not msg: msg.append("Content mismatch in existing rules.")
return ". ".join(msg)
def remediate(self, edge_id: str, source_of_truth: Dict, mode: DriftAction) -> bool:
"""
Executes rollback/sync if drift is detected based on policy.
"""
report = self.check_parity(edge_id, source_of_truth)
if not report.is_drifted:
logger.info("No drift detected. System healthy.")
return True
logger.warning(f"DRIFT DETECTED! Details: {report.details}")
if mode == DriftAction.ALERT:
logger.critical("Action is ALERT only. Sending notification...")
# Code to send Slack/Email/PagerDuty alert
return False
if mode == DriftAction.ROLLBACK:
logger.critical("Action is ROLLBACK. Force-syncing Source of Truth to Edge...")
return self.cdn.push_config(edge_id, source_of_truth)
return False
# --- 3. Unit Tests ---
import unittest
class TestDriftDetector(unittest.TestCase):
def setUp(self):
self.client = CDNClient()
self.detector = DriftDetector(self.client)
self.edge_id = "edge-123"
# Standard Source of Truth
self.truth = {
"rules": [
{"rule_id": "r1", "action": "ALLOW", "path": "/api/v1/*"},
{"rule_id": "r2", "action": "DENY", "path": "/admin/*"}
],
"origin": "https://origin.example.com"
}
def test_no_drift(self):
"""Scenario: Live config matches Truth exactly (ignoring metadata)."""
live = self.truth.copy()
live['last_updated'] = "2023-10-10T10:00:00Z" # Add noise
self.client.push_config(self.edge_id, live)
report = self.detector.check_parity(self.edge_id, self.truth)
self.assertFalse(report.is_drifted)
def test_order_irrelevant(self):
"""Scenario: Rules are in different order but logic is identical."""
live = {
"rules": [
# r2 is before r1
{"rule_id": "r2", "action": "DENY", "path": "/admin/*"},
{"rule_id": "r1", "action": "ALLOW", "path": "/api/v1/*"}
],
"origin": "https://origin.example.com"
}
self.client.push_config(self.edge_id, live)
report = self.detector.check_parity(self.edge_id, self.truth)
self.assertFalse(report.is_drifted, "Rule order should not cause drift")
def test_drift_detected_content_change(self):
"""Scenario: A rule action was changed manually on CDN."""
live = {
"rules": [
{"rule_id": "r1", "action": "DENY", "path": "/api/v1/*"}, # Changed ALLOW -> DENY
{"rule_id": "r2", "action": "DENY", "path": "/admin/*"}
],
"origin": "https://origin.example.com"
}
self.client.push_config(self.edge_id, live)
report = self.detector.check_parity(self.edge_id, self.truth)
self.assertTrue(report.is_drifted)
def test_drift_detected_missing_rule(self):
"""Scenario: A rule was deleted on CDN."""
live = {
"rules": [{"rule_id": "r1", "action": "ALLOW", "path": "/api/v1/*"}],
"origin": "https://origin.example.com"
}
self.client.push_config(self.edge_id, live)
report = self.detector.check_parity(self.edge_id, self.truth)
self.assertTrue(report.is_drifted)
self.assertIn("Missing rules", report.details)
def test_rollback_success(self):
"""Scenario: Drift occurs, system rolls back automatically."""
# 1. Simulate bad state
bad_config = {"rules": [], "origin": "bad-origin"}
self.client.push_config(self.edge_id, bad_config)
# 2. Run remediation in ROLLBACK mode
result = self.detector.remediate(self.edge_id, self.truth, mode=DriftAction.ROLLBACK)
# 3. Verify
self.assertTrue(result)
final_live = self.client.fetch_live_config(self.edge_id)
self.assertEqual(final_live['origin'], "https://origin.example.com")
# --- 4. Main Execution Example ---
if __name__ == "__main__":
# Run Tests
print("--- Running Unit Tests ---")
unittest.main(argv=['first-arg-is-ignored'], exit=False)
print("\n--- Running Live Simulation ---")
# Setup
cdn = CDNClient()
detector = DriftDetector(cdn)
edge_id = "prod-edge-01"
source_of_truth = {
"service_id": "svc-abc",
"rules": [
{"rule_id": "redirect_http", "from": "http", "to": "https"},
{"rule_id": "block_bots", "user_agent": "BadBot", "action": "block"}
]
}
# 1. Initial Deployment
print("\n[1] Initial Deployment...")
cdn.push_config(edge_id, source_of_truth)
# 2. Check Parity (Should pass)
print("\n[2] Checking Parity...")
report = detector.check_parity(edge_id, source_of_truth)
print(f"Drift Status: {report.is_drifted}")
# 3. Simulate Manual Change (Drift)
# Someone logs into the CDN dashboard and changes a rule
print("\n[3] Simulating Manual 'Bad' Change...")
drifted_config = cdn.fetch_live_config(edge_id)
# Remove a rule manually
drifted_config['rules'].pop(0)
# Add a dynamic field (CDN added this automatically)
drifted_config['last_updated'] = "2023-10-27T12:00:00Z"
cdn.push_config(edge_id, drifted_config)
# 4. Run Detector Again
print("\n[4] Running Detector with AUTO-ROLLBACK enabled...")
success = detector.remediate(edge_id, source_of_truth, mode=DriftAction.ROLLBACK)
if success:
print("\nSystem successfully recovered from configuration drift.")
else:
print("\nRemediation failed.")