We are going to design a CDN edge config drift detector that ensures the running configuration on edge nodes matches the intended configuration stored in a central version-controlled repository (e.g., Git). The system should have:
- Rule parity: The ability to define rules (in code) that describe what the configuration should be and detect drift.
- Tests: Automated tests (unit, integration) for the rules and the drift detection system.
- Rollbacks: A mechanism to roll back to a known good configuration if drift is detected.
We'll break down the implementation into components:
A. Configuration Repository (Git)
- Store intended configuration in a version-controlled repository (e.g., YAML, JSON, or code-generated).
- Use a CI/CD pipeline to validate and deploy.
B. Drift Detection Service (Edge Agent)
- Runs on each edge node (or a central service that queries edge nodes).
- Fetches the current configuration from the edge node (via CDN provider's API, or by reading local files if the CDN allows).
- Compares with the intended configuration from the repository.
C. Rule Engine
- Defines rules for what the configuration should look like. These rules can be:
- Simple key-value checks.
- Complex structural checks (e.g., using JSON schema, custom scripts).
- The rule engine should be extensible.
D. Testing Framework
- Unit tests for each rule.
- Integration tests that simulate drift scenarios.
E. Rollback Mechanism
- If drift is detected, automatically revert to the last known good configuration (from the repository) on the edge node.
- Alternatively, alert and wait for manual intervention.
F. Monitoring and Alerting
- Log drift events and send alerts (e.g., Slack, PagerDuty).
Implementation Steps:
- Design the configuration schema (what does the CDN config look like? We'll assume a simplified example).
Example: A CDN edge configuration for a service might have:
- cache_ttl: integer
- enable_compression: boolean
- allowed_origins: list of strings
- https_redirect: boolean
-
Define rules in code (using Python for example) that can validate the configuration.
-
Build a drift detector that:
a. Fetches the current configuration from the edge (we'll mock this for now).
b. Fetches the intended configuration from the repository (local file or Git clone).
c. Runs the rule engine on both and reports differences.
-
Write tests for the rules and the drift detector.
-
Implement a rollback function that can push the intended configuration to the edge.
-
Integrate with a CI/CD pipeline (e.g., GitHub Actions) to run the drift detector periodically or on deploy.
-
Add alerting.
Let's code a simplified version in Python.
Structure:
config/
rules.py - contains rule classes and functions
detector.py - the drift detector service
rollbacker.py - the rollback mechanism
tests/
test_rules.py
test_detector.py
config_schema/ - (optional) JSON schemas for configs
We assume the CDN configuration is stored in a YAML file in the repo.
Example intended config (intended.yaml):
cache_ttl: 3600
enable_compression: true
allowed_origins:
We'll create a Rule base class and then specific rules.
Rule interface:
- name: str
- check(current_config, intended_config) -> bool or raises an exception with details.
We'll also have a RuleSet that runs a collection of rules.
For rollback, we assume we have a function that can push a configuration to the edge. In reality, this would be API calls to the CDN provider.
Let's code accordingly.
Note: This is a simplified example. In production, we would have more robust error handling, logging, and security considerations.
Let's start with rules.py:
I'll design a comprehensive CDN edge configuration drift detection system with rule parity, testing, and rollback capabilities. This is a critical system for maintaining consistent, secure edge configurations.
Architecture Overview
graph TB
subgraph "Control Plane"
A[Git Repository] --> B[Config Validator]
B --> C[Rules Engine]
C --> D[Test Suite]
D --> E[CI/CD Pipeline]
end
subgraph "Data Plane"
F[Edge Nodes] --> G[Drift Detector Agent]
G --> H[Config Collector]
H --> I[Diff Engine]
I --> J[Alert Dispatcher]
end
subgraph "Orchestration"
K[Rollback Controller] --> L[Config Syncer]
L --> M[Canary Deployer]
M --> N[State Store]
end
E --> G
J --> K
N --> G
1. Core Components Implementation
Config Schema & Validation Layer
# config_validator.py
from typing import Dict, Any, List, Optional
from pydantic import BaseModel, validator, ValidationError
import json
import yaml
class EdgeConfigSchema(BaseModel):
"""Canonical schema for CDN edge configurations"""
version: str
metadata: Dict[str, Any]
rules: List[Dict[str, Any]]
variables: Dict[str, Any]
origins: List[Dict[str, Any]]
caching: Dict[str, Any]
security: Dict[str, Any]
logging: Dict[str, Any]
@validator('rules')
def validate_rules_structure(cls, v):
for rule in v:
if 'id' not in rule:
raise ValueError('Each rule must have an id')
if 'action' not in rule:
raise ValueError('Each rule must have an action')
return v
class ConfigValidator:
def __init__(self, schema_path: str = "schemas/edge_config_schema.json"):
with open(schema_path) as f:
self.schema = json.load(f)
def validate(self, config: Dict[str, Any]) -> tuple[bool, List[str]]:
"""Validate config against schema and business rules"""
errors = []
# Schema validation
try:
EdgeConfigSchema(**config)
except ValidationError as e:
errors.extend([str(err) for err in e.errors()])
# Business rule validation
errors.extend(self._validate_business_rules(config))
return len(errors) == 0, errors
def _validate_business_rules(self, config: Dict[str, Any]) -> List[str]:
errors = []
# Check for conflicting rules
rule_ids = [r['id'] for r in config.get('rules', [])]
if len(rule_ids) != len(set(rule_ids)):
errors.append("Duplicate rule IDs found")
# Check TTL bounds
for rule in config.get('rules', []):
if 'cache_ttl' in rule:
ttl = rule['cache_ttl']
if ttl < 0 or ttl > 31536000: # 1 year max
errors.append(f"Invalid TTL {ttl} in rule {rule['id']}")
return errors
Rule Parity Engine
# rules_engine.py
from abc import ABC, abstractmethod
from dataclasses import dataclass
from typing import Dict, Any, List, Optional
from datetime import datetime
import hashlib
@dataclass
class RuleResult:
rule_id: str
passed: bool
current_value: Any
expected_value: Any
diff: Optional[str] = None
timestamp: datetime = None
def __post_init__(self):
if self.timestamp is None:
self.timestamp = datetime.utcnow()
if not self.passed and self.diff is None:
self.diff = self._compute_diff()
def _compute_diff(self) -> str:
"""Compute human-readable diff"""
if type(self.current_value) != type(self.expected_value):
return f"Type mismatch: {type(self.current_value)} vs {type(self.expected_value)}"
return f"Value mismatch: {self.current_value!r} != {self.expected_value!r}"
class BaseRule(ABC):
"""Abstract base class for all drift detection rules"""
@property
@abstractmethod
def rule_id(self) -> str:
"""Unique rule identifier"""
pass
@property
@abstractmethod
def severity(self) -> str:
"""ERROR, WARNING, INFO"""
pass
@abstractmethod
def check(self, current: Dict[str, Any], expected: Dict[str, Any]) -> RuleResult:
"""Check rule compliance"""
pass
def get_metadata(self) -> Dict[str, Any]:
return {
'rule_id': self.rule_id,
'severity': self.severity,
'description': self.__doc__ or '',
'category': self.__class__.__name__
}
class ConfigHashRule(BaseRule):
"""Full config hash comparison rule"""
rule_id = "config_hash_parity"
severity = "ERROR"
def check(self, current: Dict[str, Any], expected: Dict[str, Any]) -> RuleResult:
current_hash = hashlib.sha256(
json.dumps(current, sort_keys=True).encode()
).hexdigest()
expected_hash = hashlib.sha256(
json.dumps(expected, sort_keys=True).encode()
).hexdigest()
return RuleResult(
rule_id=self.rule_id,
passed=current_hash == expected_hash,
current_value=current_hash[:8],
expected_value=expected_hash[:8],
diff=f"Hash mismatch: {current_hash[:16]}... vs {expected_hash[:16]}..."
)
class SpecificConfigRule(BaseRule):
"""Validate specific configuration keys"""
rule_id = "specific_config_parity"
severity = "ERROR"
def __init__(self, config_path: str, expected_value: Any):
self.config_path = config_path.split('.')
self.expected_value = expected_value
def _get_nested_value(self, config: Dict[str, Any], path: List[str]) -> Any:
current = config
for key in path:
if isinstance(current, dict):
current = current.get(key)
else:
return None
return current
def check(self, current: Dict[str, Any], expected: Dict[str, Any]) -> RuleResult:
current_val = self._get_nested_value(current, self.config_path)
expected_val = self._get_nested_value(expected, self.config_path)
return RuleResult(
rule_id=self.rule_id,
passed=current_val == expected_val,
current_value=current_val,
expected_value=expected_val,
diff=f"Path '{'.'.join(self.config_path)}' mismatch"
)
class RulesEngine:
def __init__(self, rules: List[BaseRule] = None):
self.rules = rules or self._get_default_rules()
self.results_cache = {}
def _get_default_rules(self) -> List[BaseRule]:
return [
ConfigHashRule(),
SpecificConfigRule('security.https_enforced', True),
SpecificConfigRule('caching.default_ttl', 3600),
# Add more default rules
]
def evaluate(self, current: Dict[str, Any], expected: Dict[str, Any]) -> List[RuleResult]:
"""Run all rules against current and expected configs"""
results = []
rule_key = self._compute_config_hash(current, expected)
# Cache results for identical config pairs
if rule_key in self.results_cache:
return self.results_cache[rule_key]
for rule in self.rules:
try:
result = rule.check(current, expected)
results.append(result)
except Exception as e:
results.append(RuleResult(
rule_id=rule.rule_id,
passed=False,
current_value=None,
expected_value=None,
diff=f"Rule execution error: {str(e)}"
))
self.results_cache[rule_key] = results
return results
def _compute_config_hash(self, current: Dict, expected: Dict) -> str:
combined = json.dumps({
'current': sorted(str(current).split()),
'expected': sorted(str(expected).split())
})
return hashlib.md5(combined.encode()).hexdigest()
Drift Detection Agent
# drift_detector.py
import time
import logging
from typing import Dict, Any, List
from concurrent.futures import ThreadPoolExecutor
import requests
from rules_engine import RulesEngine, RuleResult
class EdgeNodeClient:
"""Client to fetch config from edge nodes (CDN provider API)"""
def __init__(self, node_url: str, api_key: str):
self.node_url = node_url
self.api_key = api_key
self.session = requests.Session()
self.session.headers.update({'Authorization': f'Bearer {api_key}'})
def fetch_current_config(self) -> Dict[str, Any]:
"""Fetch live config from edge node"""
response = self.session.get(f"{self.node_url}/config")
response.raise_for_status()
return response.json()
def apply_config(self, config: Dict[str, Any]) -> bool:
"""Push config to edge node"""
response = self.session.post(
f"{self.node_url}/config/update",
json=config
)
return response.status_code == 200
class DriftDetector:
def __init__(
self,
rules_engine: RulesEngine,
config_repo: 'ConfigRepository',
node_clients: List[EdgeNodeClient],
alert_handler: 'AlertHandler'
):
self.rules_engine = rules_engine
self.config_repo = config_repo
self.node_clients = node_clients
self.alert_handler = alert_handler
self.logger = logging.getLogger(__name__)
def detect_drift(self, node_id: str) -> Dict[str, Any]:
"""Detect drift for a specific edge node"""
client = next(c for c in self.node_clients if c.node_url == node_id)
try:
current_config = client.fetch_current_config()
except Exception as e:
self.logger.error(f"Failed to fetch config from {node_id}: {e}")
return self._create_error_result(node_id, str(e))
expected_config = self.config_repo.get_active_config()
results = self.rules_engine.evaluate(current_config, expected_config)
drift_detected = any(not r.passed for r in results)
report = {
'node_id': node_id,
'timestamp': time.time(),
'drift_detected': drift_detected,
'rule_results': [r.__dict__ for r in results],
'current_config_hash': hashlib.sha256(
json.dumps(current_config, sort_keys=True).encode()
).hexdigest(),
'expected_config_hash': hashlib.sha256(
json.dumps(expected_config, sort_keys=True).encode()
).hexdigest()
}
if drift_detected:
self.alert_handler.send_alert(report)
self.logger.warning(f"Drift detected on {node_id}")
return report
def _create_error_result(self, node_id: str, error: str) -> Dict[str, Any]:
return {
'node_id': node_id,
'timestamp': time.time(),
'drift_detected': True,
'error': error,
'rule_results': []
}
Rollback Controller
# rollback_controller.py
from typing import Dict, Any, Optional
from datetime import datetime
import json
import etcd3 # or any state store
class ConfigVersion:
def __init__(self, config: Dict[str, Any], version: str,
deployed_by: str, deployed_at: datetime):
self.config = config
self.version = version
self.deployed_by = deployed_by
self.deployed_at = deployed_at
def to_dict(self):
return {
'config': self.config,
'version': self.version,
'deployed_by': self.deployed_by,
'deployed_at': self.deployed_at.isoformat()
}
class RollbackController:
def __init__(
self,
state_store: 'StateStore',
config_repo: 'ConfigRepository',
node_clients: List[EdgeNodeClient]
):
self.state_store = state_store
self.config_repo = config_repo
self.node_clients = node_clients
def rollback_node(self, node_id: str, target_version: str) -> bool:
"""Rollback a specific node to target version"""
# 1. Get target config from version store
target_config = self.state_store.get_version(target_version)
if not target_config:
raise ValueError(f"Version {target_version} not found")
# 2. Create rollback record
rollback_record = {
'node_id': node_id,
'from_version': self._get_current_version(node_id),
'to_version': target_version,
'initiated_at': datetime.utcnow().isoformat(),
'status': 'in_progress'
}
try:
# 3. Get client for node
client = next(c for c in self.node_clients if c.node_id == node_id)
# 4. Apply config
success = client.apply_config(target_config.config)
# 5. Update state
rollback_record['status'] = 'success' if success else 'failed'
rollback_record['completed_at'] = datetime.utcnow().isoformat()
self.state_store.record_rollback(rollback_record)
if success:
# Update current version in state
self.state_store.set_current_version(node_id, target_version)
return success
except Exception as e:
rollback_record['status'] = 'error'
rollback_record['error'] = str(e)
self.state_store.record_rollback(rollback_record)
return False
def _get_current_version(self, node_id: str) -> str:
"""Get current deployed version for node"""
return self.state_store.get_current_version(node_id)
def auto_rollback_on_drift(self, drift_report: Dict[str, Any]) -> bool:
"""Automatically rollback if drift detected and policy allows"""
if not self._should_auto_rollback(drift_report):
return False
node_id = drift_report['node_id']
last_good_version = self.state_store.get_last_good_version(node_id)
if last_good_version:
self.logger.info(f"Auto-rolling back {node_id} to {last_good_version}")
return self.rollback_node(node_id, last_good_version)
return False
def _should_auto_rollback(self, drift_report: Dict[str, Any]) -> bool:
"""Determine if auto-rollback should trigger based on policy"""
# Check severity of failed rules
error_rules = [
r for r in drift_report['rule_results']
if not r['passed'] and r['severity'] == 'ERROR'
]
# Auto-rollback if security rules fail
security_failures = [
r for r in error_rules
if 'security' in r['rule_id']
]
return len(security_failures) > 0
State Store (Version Tracking)
# state_store.py
from typing import Dict, Any, List, Optional
from datetime import datetime
import json
import redis # or etcd, consul, postgres
class StateStore:
def __init__(self, connection_string: str):
self.client = redis.from_url(connection_string)
self.prefix = "cdn_edge:"
def save_version(self, config: Dict[str, Any], version: str,
deployed_by: str) -> bool:
"""Save a config version"""
key = f"{self.prefix}version:{version}"
data = {
'config': config,
'version': version,
'deployed_by': deployed_by,
'deployed_at': datetime.utcnow().isoformat()
}
self.client.set(key, json.dumps(data))
return True
def get_version(self, version: str) -> Optional[Dict[str, Any]]:
"""Get specific version"""
key = f"{self.prefix}version:{version}"
data = self.client.get(key)
return json.loads(data) if data else None
def set_current_version(self, node_id: str, version: str) -> None:
"""Set current deployed version for node"""
key = f"{self.prefix}node:{node_id}:current"
self.client.set(key, version)
def get_current_version(self, node_id: str) -> str:
"""Get current deployed version for node"""
key = f"{self.prefix}node:{node_id}:current"
version = self.client.get(key)
return version.decode() if version else None
def get_versions_for_node(self, node_id: str, limit: int = 10) -> List[Dict]:
"""Get version history for node"""
# In production, use a sorted set or database table
# This is simplified
pattern = f"{self.prefix}version:*"
versions = []
for key in self.client.scan_iter(match=pattern):
data = json.loads(self.client.get(key))
if data.get('node_id') == node_id:
versions.append(data)
return sorted(versions, key=lambda x: x['deployed_at'], reverse=True)[:limit]
Test Framework
# tests/test_drift_detector.py
import pytest
from unittest.mock import Mock, patch
from drift_detector import DriftDetector, EdgeNodeClient
from rules_engine import SpecificConfigRule
class TestDriftDetection:
@pytest.fixture
def sample_config(self):
return {
'version': '1.0',
'security': {'https_enforced': True},
'caching': {'default_ttl': 3600}
}
def test_config_hash_rule_match(self, sample_config):
rule = ConfigHashRule()
result = rule.check(sample_config, sample_config.copy())
assert result.passed
assert result.diff is None
def test_config_hash_rule_mismatch(self, sample_config):
rule = ConfigHashRule()
modified = sample_config.copy()
modified['caching']['default_ttl'] = 7200
result = rule.check(sample_config, modified)
assert not result.passed
assert "Hash mismatch" in result.diff
def test_specific_config_rule_match(self):
rule = SpecificConfigRule('security.https_enforced', True)
current = {'security': {'https_enforced': True}}
expected = {'security': {'https_enforced': True}}
result = rule.check(current, expected)
assert result.passed
def test_specific_config_rule_mismatch(self):
rule = SpecificConfigRule('security.https_enforced', True)
current = {'security': {'https_enforced': False}}
expected = {'security': {'https_enforced': True}}
result = rule.check(current, expected)
assert not result.passed
assert "Value mismatch" in result.diff
@patch('drift_detector.EdgeNodeClient.fetch_current_config')
def test_drift_detection_workflow(self, mock_fetch, sample_config):
# Mock current config with drift
current_with_drift = sample_config.copy()
current_with_drift['caching']['default_ttl'] = 7200
mock_fetch.return_value = current_with_drift
config_repo = Mock()
config_repo.get_active_config.return_value = sample_config
rules_engine = RulesEngine()
alert_handler = Mock()
detector = DriftDetector(
rules_engine=rules_engine,
config_repo=config_repo,
node_clients=[EdgeNodeClient('http://node1', 'key')],
alert_handler=alert_handler
)
report = detector.detect_drift('http://node1')
assert report['drift_detected'] is True
assert alert_handler.send_alert.called
assert len(report['rule_results']) > 0
class TestRollback:
def test_successful_rollback(self):
state_store = Mock()
state_store.get_current_version.return_value = 'v2'
state_store.get_last_good_version.return_value = 'v1'
config_repo = Mock()
good_config = {'version': '1.0', 'caching': {'default_ttl': 3600}}
config_repo.get_active_config.return_value = good_config
node_client = Mock()
node_client.apply_config.return_value = True
controller = RollbackController(
state_store=state_store,
config_repo=config_repo,
node_clients=[node_client]
)
result = controller.rollback_node('node1', 'v1')
assert result is True
node_client.apply_config.assert_called_once_with(good_config)
CI/CD Pipeline Integration
# .github/workflows/config-drift.yml
name: CDN Config Drift Detection
on:
schedule:
- cron: '*/15 * * * *' # Every 15 minutes
push:
branches: [main]
paths: ['configs/**', 'rules/**']
workflow_dispatch:
jobs:
validate-config:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.9'
- name: Install dependencies
run: |
pip install -r requirements.txt
- name: Validate config schema
run: |
python -m config_validator validate --file configs/edge_prod.yaml
- name: Run rule tests
run: |
pytest tests/test_rules.py -v
- name: Dry-run drift detection
run: |
python -m drift_detector --dry-run --config configs/edge_prod.yaml
deploy-config:
needs: validate-config
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v3
- name: Deploy to canary nodes
run: |
python -m deployer --canary --nodes canary-1,canary-2
- name: Run integration tests
run: |
pytest tests/test_integration.py --nodes canary-1,canary-2
- name: Full rollout if healthy
if: success()
run: |
python -m deployer --full --nodes all
Alerting & Observability
# alerting.py
from typing import Dict, Any, List
from dataclasses import dataclass
from enum import Enum
import smtplib
import requests
class AlertSeverity(Enum):
CRITICAL = "critical"
ERROR = "error"
WARNING = "warning"
INFO = "info"
@dataclass
class Alert:
title: str
description: str
severity: AlertSeverity
metadata: Dict[str, Any]
timestamp: str
class AlertHandler:
def __init__(self, config: Dict[str, Any]):
self.config = config
self.suppression_window = 300 # 5 minutes
def send_alert(self, drift_report: Dict[str, Any]):
"""Send alert based on drift report"""
alerts = self._generate_alerts(drift_report)
for alert in alerts:
if self._should_suppress(alert):
continue
# Send to multiple channels
self._send_slack(alert)
self._send_pagerduty(alert)
self._send_email(alert)
self._log_alert(alert)
def _generate_alerts(self, report: Dict[str, Any]) -> List[Alert]:
alerts = []
for rule_result in report.get('rule_results', []):
if not rule_result['passed']:
severity = AlertSeverity.ERROR
if 'security' in rule_result['rule_id']:
severity = AlertSeverity.CRITICAL
elif 'warning' in rule_result.get('severity', '').lower():
severity = AlertSeverity.WARNING
alerts.append(Alert(
title=f"Config drift detected: {rule_result['rule_id']}",
description=rule_result['diff'],
severity=severity,
metadata={
'node_id': report['node_id'],
'rule_id': rule_result['rule_id'],
'current': str(rule_result['current_value'])[:100],
'expected': str(rule_result['expected_value'])[:100]
},
timestamp=report['timestamp']
))
return alerts
def _should_suppress(self, alert: Alert) -> bool:
"""Check if alert should be suppressed (deduplication)"""
# Implement deduplication logic
return False
2. Deployment & Operations
Docker Compose for Local Testing
# docker-compose.test.yml
version: '3.8'
services:
drift-detector:
build: .
environment:
- STATE_STORE_URL=redis://redis:6379
- CONFIG_REPO_PATH=/configs
- NODE_ENDPOINTS=http://edge-node-1:8080,http://edge-node-2:8080
volumes:
- ./configs:/configs:ro
command: ["python", "-m", "drift_detector", "--monitor"]
redis:
image: redis:7-alpine
ports:
- "6379:6379"
prometheus:
image: prom/prometheus
volumes:
- ./prometheus.yml:/etc/prometheus/prometheus.yml
ports:
- "9090:9090"
grafana:
image: grafana/grafana
ports:
- "3000:3000"
Prometheus Metrics
# metrics.py
from prometheus_client import Counter, Gauge, Histogram, start_http_server
DRIFT_DETECTED = Counter('cdn_drift_detected_total',
'Total number of drift detections',
['node_id', 'rule_id', 'severity'])
CONFIG_VERSIONS = Gauge('cdn_config_versions',
'Number of config versions', ['node_id'])
ROLLBACKS = Counter('cdn_rollbacks_total',
'Total rollbacks performed',
['node_id', 'target_version'])
CHECK_DURATION = Histogram('cdn_drift_check_seconds',
'Drift check duration')
class MetricsCollector:
def __init__(self, port: int = 8000):
start_http_server(port)
def record_drift(self, node_id: str, rule_id: str, severity: str):
DRIFT_DETECTED.labels(node_id=node_id, rule_id=rule_id, severity=severity).inc()
def record_rollback(self, node_id: str, target_version: str):
ROLLBACKS.labels(node_id=node_id, target_version=target_version).inc()
def time_check(self):
return CHECK_DURATION.time()
3. Security Considerations
- Authentication: All API calls to edge nodes require mutual TLS or API keys
- Secrets Management: Use HashiCorp Vault/AWS Secrets Manager for credentials
- Audit Logging: All config changes logged with user context
- RBAC: Role-based access control for rollback operations
- Network Security: Drift detector runs in private VPC/subnet
4. Operational Runbook
Drift Response Procedure
-
Detection Phase:
- Drift detector runs every 5 minutes (configurable)
- Critical drifts trigger immediate PagerDuty alerts
- Non-critical drifts create JIRA tickets
-
Analysis Phase:
# Check drift details
curl http://drift-detector:8080/api/v1/report?node=edge-node-1
# Get config diff
python -m config_diff --node=edge-node-1 --output=json
-
Remediation:
-
Post-Mortem:
- Investigate root cause (manual change? bug?)
- Update rules to prevent recurrence
- Adjust rollback policies if needed
5. Configuration Example
# configs/edge_prod.yaml
version: "2.1.0"
metadata:
environment: production
region: us-west-2
owner: "cdn-team"
rules:
- id: "compression-rule"
action: "compress"
conditions:
- "response.status in [200, 201]"
- "response.content_type in ['text/html', 'application/json']"
parameters:
gzip: true
brotli: true
- id: "cache-static"
action: "cache"
match:
url_pattern: "^/static/.*\\.(js|css|png|jpg)$"
parameters:
ttl: 86400
edge_ttl: 3600
variables:
- key: "API_ENDPOINT"
value: "https://api.example.com"
protected: true
security:
https_enforced: true
hsts_max_age: 31536000
cors_policy:
allowed_origins: ["https://example.com"]
allowed_methods: ["GET", "POST", "OPTIONS"]
caching:
default_ttl: 3600
stale_ttl: 1800
bypass_cache: ["/admin/*", "/api/*"]
Key Features Implemented:
- Rule Parity: Schema validation + custom rules engine with extensible rule types
- Automated Testing: Unit/integration tests + CI/CD integration
- Safe Rollbacks: Version tracking + canary deployments + auto-rollback on critical drifts
- Observability: Prometheus metrics + structured logging + alerting
- Security: Schema validation + input sanitization + RBAC
- Operational Excellence: Runbooks + dry-run mode + gradual rollouts
This system provides enterprise-grade drift detection with the safety mechanisms needed for production CDN edge configurations. The modular design allows easy extension for different CDN providers (Cloudflare, Akamai, Fastly, etc.) through the EdgeNodeClient abstraction.