python
from dataclasses import dataclass
from enum import Enum
from typing import Dict, List, Any, Optional, Callable, Set, Tuple
from functools import wraps
import hashlib
import json
import time
class PolicyDecision(Enum):
"""Policy decisions: ALLOW permits, DENY forbids, ABSTAIN skips."""
ALLOW = "allow"
DENY = "deny"
ABSTAIN = "abstain"
@dataclass
class AuditEntry:
"""Audit log entry for a single policy evaluation."""
policy_name: str
decision: PolicyDecision
reason: str
timestamp: float = 0.0
def __post_init__(self):
if self.timestamp == 0.0:
self.timestamp = time.time()
@dataclass
class CheckResult:
"""Result of an authorization check."""
allowed: bool
"""True if access is allowed."""
reasons: List[str]
"""Human-readable reasons for the decision."""
audit: List[AuditEntry]
"""Detailed audit trail."""
@dataclass(frozen=True) # Hashable for caching
class Subject:
id: str
roles: List[str]
attributes: Dict[str, Any]
@dataclass(frozen=True)
class Action:
name: str
@dataclass(frozen=True)
class Resource:
id: str
attributes: Dict[str, Any]
owner: Optional[str]
@dataclass(frozen=True)
class Context:
env: Dict[str, Any]
@dataclass
class Stores:
"""Stores for policy data (RBAC roles/perms, ReBAC relations). Mutable."""
rbac_user_roles: Dict[str, Set[str]] = None # user_id -> set(roles)
role_permissions: Dict[str, Set[str]] = None # role -> set(perms like "read:doc")
relations: Dict[str, Dict[str, Set[str]]] = None # resource_id -> {rel: set(user_ids)}
def __post_init__(self):
if self.rbac_user_roles is None:
self.rbac_user_roles = {}
if self.role_permissions is None:
self.role_permissions = {}
if self.relations is None:
self.relations = {}
# Policy type: composable function
Policy = Callable[[Subject, Action, Resource, Context, Stores], PolicyDecision]
class AuthzEngine:
"""
Composable authorization engine supporting RBAC/ABAC/ReBAC.
- Add policies with `add_policy(name, policy_func)`.
- Policies evaluate in order; first DENY wins, else ALLOW if any, else deny.
- Caching based on subject/action/resource/context key (ignores store changes).
- Audit trail per check.
- For production: add cache invalidation, persistent stores, async audit.
"""
def __init__(self, max_cache_size: int = 1000):
self.policies: List[Policy] = []
self.policy_names: List[str] = []
self.cache: Dict[str, CheckResult] = {}
self.max_cache_size = max_cache_size
self.audit_callback: Optional[Callable[[CheckResult, str], None]] = None
"""Optional callback for audit logging (check_key, result)."""
def add_policy(self, name: str, policy: Policy) -> None:
"""Register a composable policy."""
self.policy_names.append(name)
self.policies.append(policy)
def check(self, subject: Subject, action: Action, resource: Resource,
context: Context, stores: Stores) -> CheckResult:
"""Evaluate authorization."""
key = self._make_cache_key(subject, action, resource, context)
if key in self.cache:
return self.cache[key]
decisions: List[PolicyDecision] = []
audit: List[AuditEntry] = []
reasons: List[str] = []
for name, policy in zip(self.policy_names, self.policies):
try:
decision = policy(subject, action, resource, context, stores)
decisions.append(decision)
reason = f"{name}: {decision.value}"
reasons.append(reason)
audit.append(AuditEntry(name, decision, reason))
except Exception as e:
err_reason = f"{name}: error - {str(e)}"
reasons.append(err_reason)
audit.append(AuditEntry(name, PolicyDecision.ABSTAIN, err_reason))
# Decision logic: explicit DENY wins; else ALLOW if any; else deny
has_deny = PolicyDecision.DENY in decisions
has_allow = PolicyDecision.ALLOW in decisions
allowed = not has_deny and has_allow
if not decisions:
reasons = ["No policies matched."]
result = CheckResult(allowed, reasons, audit)
# Cache (LRU-like eviction)
self.cache[key] = result
if len(self.cache) > self.max_cache_size:
# Evict oldest (simple: remove first key)
first_key = next(iter(self.cache))
del self.cache[first_key]
# Emit audit
if self.audit_callback:
self.audit_callback(key, result)
return result
def clear_cache(self) -> None:
"""Clear cache (e.g., after store mutations)."""
self.cache.clear()
def _make_cache_key(self, subject: Subject, action: Action,
resource: Resource, context: Context) -> str:
"""Deterministic cache key."""
# Hashable serialization
def serialize(obj: Any) -> str:
if isinstance(obj, dict):
return json.dumps(obj, sort_keys=True, default=str)
return str(obj)
parts = [
subject.id,
action.name,
resource.id,
serialize({k: v for k, v in subject.attributes.items() if isinstance(v, (str, int, float, bool))}),
serialize({k: v for k, v in resource.attributes.items() if isinstance(v, (str, int, float, bool))}),
serialize({k: v for k, v in context.env.items() if isinstance(v, (str, int, float, bool))}),
]
key_str = ":".join(parts)
return hashlib.md5(key_str.encode()).hexdigest()
# Pre-built policies (RBAC, ABAC, ReBAC)
def rbac_policy(subject: Subject, action: Action, resource: Resource,
context: Context, stores: Stores) -> PolicyDecision:
"""RBAC: Check user roles -> permissions (perm format: "read:doc")."""
user_roles = set(subject.roles) | stores.rbac_user_roles.get(subject.id, set())
resource_type = resource.attributes.get("type", "any")
required_perm = f"{action.name}:{resource_type}"
for role in user_roles:
if required_perm in stores.role_permissions.get(role, set()):
return PolicyDecision.ALLOW
return PolicyDecision.ABSTAIN
def abac_policy(subject: Subject, action: Action, resource: Resource,
context: Context, stores: Stores) -> PolicyDecision:
"""ABAC: Example - same dept + business hours."""
user_dept = subject.attributes.get("dept")
res_dept = resource.attributes.get("dept")
if user_dept == res_dept:
hour = context.env.get("hour", 25)
if 9 <= hour <= 17:
return PolicyDecision.ALLOW
else:
return PolicyDecision.DENY # Explicit deny after hours
return PolicyDecision.ABSTAIN
def rebac_policy(subject: Subject, action: Action, resource: Resource,
context: Context, stores: Stores) -> PolicyDecision:
"""ReBAC: Check relations (e.g., action 'read' requires 'reader'|'owner' rel)."""
rel_map: Dict[str, List[str]] = {
"read": ["reader", "editor", "owner"],
"write": ["editor", "owner"],
"delete": ["owner"],
}
required_rels = rel_map.get(action.name, [])
resource_rels = stores.relations.get(resource.id, {})
for rel in required_rels:
if subject.id in resource_rels.get(rel, set()):
return PolicyDecision.ALLOW
return PolicyDecision.ABSTAIN
# Example usage
if __name__ == "__main__":
# Setup
engine = AuthzEngine(max_cache_size=10)
engine.add_policy("RBAC", rbac_policy)
engine.add_policy("ABAC", abac_policy)
engine.add_policy("ReBAC", rebac_policy)
stores = Stores(
rbac_user_roles={"alice": {"admin"}, "bob": {"user"}},
role_permissions={
"admin": {"read:any", "write:any"},
"user": {"read:doc"}
},
relations={
"doc1": {
"reader": {"alice", "charlie"},
"owner": {"bob"}
}
}
)
# Test cases
subject_alice = Subject("alice", ["editor"], {"dept": "eng"})
action_read = Action("read")
resource_doc1 = Resource("doc1", {"type": "doc", "dept": "eng"}, "bob")
ctx_day = Context({"hour": 10})
ctx_night = Context({"hour": 20})
print("=== Alice read doc1 (day) ===")
result1 = engine.check(subject_alice, action_read, resource_doc1, ctx_day, stores)
print(f"Allowed: {result1.allowed}")
print(f"Reasons: {result1.reasons}")
print("Audit:", [(e.policy_name, e.decision.value) for e in result1.audit])
print("\n=== Same, night ===")
result2 = engine.check(subject_alice, action_read, resource_doc1, ctx_night, stores)
print(f"Allowed: {result2.allowed} (ABAC denies)")
print("\n=== Cached? ===")
result3 = engine.check(subject_alice, action_read, resource_doc1, ctx_day, stores)
print(f"Allowed: {result3.allowed} (cached)")
# Custom deny policy example
def blacklist_policy(s: Subject, a: Action, r: Resource, c: Context, stores: Stores) -> PolicyDecision:
blacklist = {"mallory"}
if s.id in blacklist:
return PolicyDecision.DENY
return PolicyDecision.ABSTAIN
engine.add_policy("Blacklist", blacklist_policy)
subject_mallory = Subject("mallory", [], {})
result_deny = engine.check(subject_mallory, action_read, resource_doc1, ctx_day, stores)
print(f"\n=== Mallory ===")
print(f"Allowed: {result_deny.allowed} (blacklist DENY wins)")
For production: Add TTL cache (cachetools), async audit, Zanzibar-like graph (e.g., SpiceDB), JWT integration. Test with pytest! 🚀