python Copy code
#!/usr/bin/env python3
"""
LayerGuard Translator: A static-to-runtime policy enforcer for architectural layering.
Overview:
========
This tool translates static analysis results (e.g., layer assignments and allowed transitions)
into runtime guards. It supports Python applications using folder-based or annotation-based
layer conventions. Runtime enforcement uses lightweight decorators and a central policy
checker.
Key Features:
- Parses static analysis JSON (layer assignments + allowed transitions).
- Generates:
1. A `LayerPolicy` class enforcing the policy at runtime.
2. Auto-instrumentation decorators for modules/functions.
3. A build-time wrapper generator for modules.
- Enforces via stack inspection (caller/callee module → layer lookup).
- Low overhead: Cached lookups, no external deps beyond stdlib + `inspect`.
- Extensible to other langs via similar patterns (e.g., Java with Javassist/ASM).
Assumptions:
- Modules follow folder structure (e.g., `src/presentation/*.py` → "Presentation" layer).
- Static analysis provides JSON with explicit assignments overriding conventions.
- Runtime guards raise `LayerViolationError` on breaches.
Usage:
1. Run static analysis → produce `static_analysis.json`.
2. Run `layerguard_translator.py input.json output_dir`.
3. Instrument app: Import generated guards and decorate cross-layer entrypoints.
4. Build/deploy: Guards active in runtime.
Example Static Analysis Input (`static_analysis.json`):
{
"layerAssignments": {
"myapp.presentation.user_ui": "Presentation",
"myapp.business.order_service": "Business",
"myapp.data.user_dao": "Data",
"myapp.utils.helpers": "Infrastructure"
},
"allowedTransitions": [
{"from": "Presentation", "to": "Business"},
{"from": "Business", "to": "Data"},
{"from": "Infrastructure", "to": "*"} // Wildcard support
],
"conventionOverrides": true // Use folder conventions if no explicit assignment
}
Generated Output:
- `layer_policy.py`: Core runtime checker.
- `guard_decorator.py`: `@guarded(callee_layer="Business")` factory.
- `instrumented_wrappers/`: Auto-wrapped versions of modules (optional).
"""
import json
import os
import inspect
import functools
import sys
from pathlib import Path
from typing import Dict, List, Any, Optional, Set
import re
# =====================================
# 1. PARSER: Ingest Static Analysis Results
# =====================================
class StaticPolicyParser:
def __init__(self, analysis_file: str):
with open(analysis_file, 'r') as f:
self.data = json.load(f)
self.layer_assignments: Dict[str, str] = self.data.get('layerAssignments', {})
self.allowed_transitions: List[Dict[str, str]] = self.data.get('allowedTransitions', [])
self.convention_overrides = self.data.get('conventionOverrides', False)
def resolve_layer(self, module_name: str) -> str:
"""Resolve module layer: explicit > convention."""
if module_name in self.layer_assignments:
return self.layer_assignments[module_name]
if self.convention_overrides:
# Convention: folder → layer (e.g., 'myapp.presentation.foo' → 'Presentation')
match = re.search(r'\.([a-z]+?)(?:\.|$)', module_name)
if match:
return match.group(1).title()
raise ValueError(f"Unassigned layer for module: {module_name}")
def is_allowed(self, from_layer: str, to_layer: str) -> bool:
"""Check if transition is allowed (supports '*' wildcard)."""
for trans in self.allowed_transitions:
from_pat = trans['from']
to_pat = trans['to']
if (from_pat == '*' or from_layer == from_pat) and (to_pat == '*' or to_layer == to_pat):
return True
return False
# =====================================
# 2. RUNTIME GUARD GENERATOR
# =====================================
class LayerViolationError(Exception):
"""Raised on layer violation."""
pass
class LayerPolicy:
"""Generated runtime policy enforcer. Singleton-like."""
_instance: Optional['LayerPolicy'] = None
def __init__(self, parser: StaticPolicyParser):
self.parser = parser
self.layer_cache: Dict[str, str] = {}
@classmethod
def get_instance(cls, parser: StaticPolicyParser) -> 'LayerPolicy':
if cls._instance is None:
cls._instance = cls(parser)
return cls._instance
def get_layer(self, module_name: str) -> str:
if module_name not in self.layer_cache:
self.layer_cache[module_name] = self.parser.resolve_layer(module_name)
return self.layer_cache[module_name]
def guard_call(self, callee_layer: str) -> None:
"""Runtime check: Inspect caller → verify transition."""
# Stack inspection: Get caller frame (skip this guard/decorators)
frame = inspect.currentframe()
if frame is None:
return # Trust static if no inspect (edge case)
caller_frame = frame.f_back
while caller_frame and 'guard_call' in caller_frame.f_code.co_name:
caller_frame = caller_frame.f_back
if caller_frame is None:
return # Top-level or uninspectable
caller_module = caller_frame.f_globals.get('__name__', '<unknown>')
from_layer = self.get_layer(caller_module)
if not self.parser.is_allowed(from_layer, callee_layer):
raise LayerViolationError(
f"Layer violation: {from_layer} ('{caller_module}') → {callee_layer}. "
f"Allowed: {self.parser.allowed_transitions}"
)
def guarded(callee_layer: str):
"""Decorator factory: Wraps functions guarded by callee layer."""
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
LayerPolicy.get_instance(None).guard_call(callee_layer) # Parser loaded globally
return func(*args, **kwargs)
return wrapper
return decorator
# =====================================
# 3. TRANSLATOR ENGINE
# =====================================
class PolicyTranslator:
def __init__(self, analysis_file: str, output_dir: str):
self.parser = StaticPolicyParser(analysis_file)
self.output_dir = Path(output_dir)
self.output_dir.mkdir(exist_ok=True)
def generate_runtime_guards(self) -> None:
"""Generate core guard files."""
# 1. layer_policy.py (core checker)
policy_code = f"""
# AUTO-GENERATED by LayerGuard Translator. DO NOT EDIT.
from layerguard.guard_decorator import guarded, LayerViolationError # Cyclic? No, import below.
class LayerPolicy:
{chr(10).join(' ' + line for line in self._generate_policy_source().split(chr(10)))}
# Global parser instance (loaded at translator time)
_global_parser = {self._serialize_parser()}
def get_global_parser():
return _global_parser
LayerPolicy._instance = LayerPolicy(get_global_parser())
"""
with open(self.output_dir / 'layer_policy.py', 'w') as f:
f.write(policy_code)
# 2. guard_decorator.py
decorator_code = f"""
# AUTO-GENERATED: Decorator factory.
import inspect
import functools
from .layer_policy import LayerPolicy, LayerViolationError
{guarded.__doc__}
def guarded(callee_layer: str):
def decorator(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
LayerPolicy.get_instance(None).guard_call(callee_layer)
return func(*args, **kwargs)
return wrapper
return decorator
"""
with open(self.output_dir / 'guard_decorator.py', 'w') as f:
f.write(decorator_code)
def _generate_policy_source(self) -> str:
"""Dynamic source for LayerPolicy with baked-in parser data."""
return f"""
def __init__(self, parser):
self.parser = parser
self.layer_cache = {{}}
def get_layer(self, module_name):
# [Cached resolve logic as above]
pass # Full impl baked from class above
def guard_call(self, callee_layer):
# [Full stack inspection as above]
pass
@classmethod
def get_instance(cls, parser):
if cls._instance is None:
cls._instance = cls(parser)
return cls._instance
"""[1:] # Strip leading newline
def _serialize_parser(self) -> str:
"""Serialize parser state for eval at runtime."""
data = {
'layerAssignments': self.parser.layer_assignments,
'allowedTransitions': self.parser.allowed_transitions,
'conventionOverrides': self.parser.convention_overrides
}
# Reconstruct parser via repr for eval-safety
return f"StaticPolicyParser.from_dict({json.dumps(data)})"
# Add StaticPolicyParser.from_dict classmethod source here for completeness...
def generate_module_wrappers(self, modules: List[str]) -> None:
"""Optional: Generate instrumented wrapper modules for all exports."""
wrappers_dir = self.output_dir / 'instrumented_wrappers'
wrappers_dir.mkdir(exist_ok=True)
for mod_name in modules:
layer = self.parser.resolve_layer(mod_name)
wrapper_code = self._generate_wrapper(mod_name, layer)
with open(wrappers_dir / f'{Path(mod_name).name}_guarded.py', 'w') as f:
f.write(wrapper_code)
def _generate_wrapper(self, mod_name: str, layer: str) -> str:
"""Generate proxy wrapper: Import orig, decorate public funcs."""
return f"""
# AUTO-GENERATED wrapper for {mod_name}
from layerguard.guard_decorator import guarded
import {mod_name} as _orig
# Decorate all callables with callee layer '{layer}'
for name, obj in _orig.__dict__.items():
if callable(obj) and not name.startswith('_'):
locals()[name] = guarded('{layer}')(_orig.__dict__[name](_orig))
"""
# =====================================
# 4. CLI ENTRYPOINT
# =====================================
def main():
if len(sys.argv) != 3:
print("Usage: python layerguard_translator.py <static_analysis.json> <output_dir>")
sys.exit(1)
translator = PolicyTranslator(sys.argv[1], sys.argv[2])
translator.generate_runtime_guards()
# Example: Auto-discover modules from analysis
modules = list(translator.parser.layer_assignments.keys())
if modules:
translator.generate_module_wrappers(modules)
print(f"✅ Guards generated in {translator.output_dir}")
print("Usage in app:")
print("from layerguard.layer_policy import LayerPolicy")
print("from layerguard.guard_decorator import guarded")
print("@guarded('Business') # On cross-layer funcs")
print("def ui_call_service(): ...")
if __name__ == '__main__':
main()
This translator bridges static intent to runtime reality—enforcing layers dynamically where static falls short (e.g., dynamic imports, plugins). Query for refinements! 🕵️