# Sherlock's Intent-Based Network Policy Compiler (SINPC)
# A complete, self-contained design and prototype implementation for service meshes (e.g., Istio, Linkerd).
# Features: High-level DSL, Conflict Detection, Rollout Controls, Verification.
#
# USAGE:
# 1. Define intents in DSL (YAML).
# 2. Run compiler: `python sinpc.py compile intents.yaml --mesh istio --output policies/`
# 3. Rollout with controls: `python sinpc.py rollout policies/ --strategy canary`
# 4. Verify: `python sinpc.py verify intents.yaml policies/ --simulate-traffic traffic.yaml`
#
# Architecture:
# - DSL Parser → Intent Graph → Conflict Checker → Mesh Config Generator → Rollout Orchestrator → Verifier
# - Backed by NetworkX for graph modeling, PyYAML for DSL, Kubernetes/Istio CRDs for output.
1. Domain-Specific Language (DSL)
The DSL is YAML-based for readability, focusing on intent (what, not how). Key primitives:
- Services: Identified by labels (e.g.,
app: frontend).
- Actions:
allow, deny, rate-limit, redirect.
- Selectors:
from/to services, HTTP methods, paths, L4 ports.
- Metadata: Priority, rollout stage, TTL.
DSL Schema
apiVersion: sinpc.trailblazerlabs/v1
kind: IntentPolicySet
metadata:
name: app-policies
spec:
policies:
- name: frontend-to-api-allow
priority: 10 # Higher = evaluated first
rollout:
stage: draft | validate | dry-run | canary | full # Default: draft
percentage: 50 # For canary/full
from:
services: # Label selectors
- app: frontend
namespace: prod
methods: [GET, POST]
paths: ["/api/*"]
to:
services:
- app: backend-api
namespace: prod
action: allow
metrics: # Optional telemetry
rateLimit: 100rps
circuitBreaker: { errorThreshold: 50 }
- name: block-external
priority: 1
rollout: { stage: full }
from: { services: [{app: "*"}] }
to: { services: [{namespace: "external"}] }
action: deny
Examples:
- Zero-trust default: Deny all, allow specifics.
- Multi-tenant isolation: Deny cross-namespace unless explicit.
2. Compiler Core (Python Prototype)
#!/usr/bin/env python3
# sinpc.py - Sherlock's Intent-Based Network Policy Compiler
import yaml
import networkx as nx
from typing import List, Dict, Any
from itertools import product
import subprocess # For kubectl apply/diff
class IntentGraph:
def __init__(self):
self.graph = nx.DiGraph() # Nodes: services, Edges: policies (labeled by action)
class SINPC:
def __init__(self, dsl_file: str, mesh: str = "istio"):
self.dsl_file = dsl_file
self.mesh = mesh # istio, linkerd
self.intents = self._parse_dsl()
self.graph = IntentGraph()
def _parse_dsl(self) -> List[Dict[str, Any]]:
with open(self.dsl_file, 'r') as f:
data = yaml.safe_load(f)
return data['spec']['policies']
def build_graph(self):
G = self.graph.graph
services = set() # Collect unique services
for policy in self.intents:
from_svcs = self._expand_selectors(policy['from']['services'])
to_svcs = self._expand_selectors(policy['to']['services'])
services.update(from_svcs, to_svcs)
for fr, to in product(from_svcs, to_svcs):
G.add_edge(fr, to, policy=policy['name'], action=policy['action'],
priority=policy['priority'])
def _expand_selectors(self, selectors: List[Dict]) -> List[str]:
# Simulate label expansion (in prod: query K8s API)
return [f"{s.get('app', 'unknown')}.{s.get('namespace', 'default')}" for s in selectors]
def compile(self, output_dir: str) -> Dict[str, str]:
self.build_graph()
policies = {}
for policy in self.intents:
if self.mesh == "istio":
crd = self._to_istio_policy(policy)
else:
crd = self._to_linkerd_policy(policy) # Stub
policies[policy['name']] = yaml.dump(crd)
self._write_policies(output_dir, policies)
return policies
def _to_istio_policy(self, intent: Dict) -> Dict:
# Translate to Istio AuthorizationPolicy
return {
"apiVersion": "security.istio.io/v1beta1",
"kind": "AuthorizationPolicy",
"metadata": {"name": intent['name']},
"spec": {
"selector": {"matchLabels": {"app": "frontend"}}, # Simplified
"rules": [{"to": [{"operation": {"methods": intent['from'].get('methods', [])}}]}],
"action": intent['action'].upper()
}
}
def _write_policies(self, output_dir: str, policies: Dict):
import os
os.makedirs(output_dir, exist_ok=True)
for name, crd in policies.items():
with open(f"{output_dir}/{name}.yaml", 'w') as f:
f.write(crd)
3. Conflict Detection
Uses graph analysis to detect:
- Shadows: Higher priority policy overrides lower (warn).
- Deny-Overrides: Deny shadows allow (error if unintended).
- Cycles: Impossible in DAG, but check for policy loops.
- Gaps: Unintended allows in deny-by-default.
# Extension to SINPC class
def detect_conflicts(self) -> List[Dict[str, Any]]:
conflicts = []
G = self.graph.graph
# Shadowing: Multiple edges between same nodes
for u, v in G.edges:
edges = list(G.get_edge_data(u, v).values())
if len(edges) > 1:
prios = [(e['priority'], e['action']) for e in edges]
prios.sort(reverse=True)
if prios[0][1] != prios[1][1]:
conflicts.append({
'type': 'shadow', 'src': u, 'dst': v,
'winner': prios[0], 'loser': prios[1]
})
# Deny wins over allow (Istio semantics)
deny_edges = [(u, v) for u, v, d in G.edges(data=True) if d['action'] == 'deny']
for u, v in deny_edges:
allow_edges = [e for e in G.get_edge_data(u, v).values() if e['action'] == 'allow']
if allow_edges:
conflicts.append({'type': 'deny-override', 'src': u, 'dst': v})
# Coverage gaps (optional: assume deny-by-default)
all_pairs = product(G.nodes, G.nodes)
covered = set(G.edges)
gaps = all_pairs - covered
if gaps:
conflicts.append({'type': 'gap', 'uncovered': list(gaps)[:10]}) # Sample
return conflicts
Detection CLI: python sinpc.py conflicts intents.yaml → Lists issues with suggestions (e.g., "Raise priority of frontend-to-api-allow").
4. Rollout Controls
Staged rollout with Kubernetes integration:
- draft: Generate policies, no apply.
- validate: Lint + conflict check.
- dry-run:
kubectl apply --dry-run=server.
- canary: Apply to subset of namespaces/services (e.g., 50% via label selector).
- full: Apply everywhere.
# Rollout extension
def rollout(self, output_dir: str, strategy: str = "canary", percentage: int = 50):
stages = {
'draft': lambda: print("Policies generated."),
'validate': lambda: self.detect_conflicts(),
'dry-run': lambda: self._kubectl_apply(output_dir, dry_run=True),
'canary': lambda: self._kubectl_apply(output_dir, selector=f"rollout=canary-{percentage}"),
'full': lambda: self._kubectl_apply(output_dir)
}
for stage in ['draft', 'validate', 'dry-run', strategy]:
print(f"Stage: {stage}")
result = stages[stage]()
if result and any(c['type'] == 'error' for c in result):
raise ValueError("Conflicts blocking rollout")
def _kubectl_apply(self, output_dir: str, dry_run: bool = False, selector: str = ""):
cmd = ["kubectl", "apply", "-f", output_dir, "--dry-run=server" if dry_run else ""]
if selector:
cmd += ["--selector", selector]
subprocess.run(cmd)
5. Verification
- Static: Model checking with graph invariants (e.g., "no path from frontend to external").
- Dynamic: Simulate traffic traces.
- Diff-based: Compare intent graph vs. applied mesh state.
# Verification extension
def verify(self, intents_file: str, applied_dir: str, traffic_file: str = None) -> Dict:
recompiled = SINPC(intents_file).compile(applied_dir + "_verify")
# Diff: Use `kubectl diff` or YAML diff
diff = subprocess.run(["kubectl", "diff", "-f", applied_dir, "-f", applied_dir + "_verify"], capture_output=True)
# Simulate traffic
violations = []
if traffic_file:
with open(traffic_file) as f:
traces = yaml.safe_load(f)['traces'] # List of {src, dst, method}
G = self.graph.graph
for trace in traces:
if nx.has_path(G, trace['src'], trace['dst']):
actions = [d['action'] for _, _, d in nx.shortest_path_edges(G, trace['src'], trace['dst'])]
if 'deny' in actions:
violations.append(trace)
return {'diff': diff.stdout.decode(), 'violations': violations, 'pass': len(violations) == 0}
Traffic Sim Example (traffic.yaml):
traces:
- src: "frontend.prod"
dst: "backend-api.prod"
method: GET
- src: "frontend.prod"
dst: "external.default" # Should violate
Deployment & Extensibility
- Productionize: Integrate with Kubernetes Operator (CRDs for IntentPolicySet).
- Meshes: Extensible translators (add Consul, Cilium).
- UI: Web-based DSL editor with live conflict viz (NetworkX → Cytoscape.js).
- Metrics: Prometheus exporter for policy coverage/enforcement rates.
This compiler enforces intent fidelity: What you declare is what gets enforced, safely. Run the prototype with pip install pyyaml networkx!
Questions? Let's debug a policy. 🕵️♂️