The user wants me to design a granular Role-Based Access Control (RBAC) policy diff engine.
Key features requested:
- Granular Diffs: Ability to compare policies at a detailed level (who, what, resource, condition).
- Blast Radius Previews: Visualization or analysis of what exactly changes if this policy is applied (which users, which resources).
- Simulation Mode: "Dry run" capability to test the policy against real or hypothetical requests without enforcing it.
- Approval Workflows: A mechanism for changes to be reviewed and signed off before merging.
Target Architecture:
I need to conceptualize this as a system design proposal or a core engine implementation. Given the complexity, a Python-based class structure implementing the core logic, backed by a conceptual architecture explanation, is the best approach.
Key Components to Design:
-
Policy Representation: How are RBAC policies stored? (JSON/YAML is standard).
- Structure: Subject (User/Group), Action (Read/Write), Resource (Path/ARN), Condition (Time/IP).
-
Diffing Engine:
- Input:
current_policy.json, proposed_policy.json.
- Logic: Set theory operations (Additions, Removals, Modifications).
- Output: A structured diff object.
-
Blast Radius Calculator:
- This requires state. We need a snapshot of the User Directory and Resource Inventory.
- Logic: Resolve the proposed policy against the directory to see who gets new access or loses access.
-
Simulator (The "Policy Decision Point" or PDP):
- Input: Subject, Action, Resource, Context.
- Logic: Run the request through the proposed policy to see
ALLOW or DENY.
-
Workflow Engine:
- States:
Draft -> Pending Approval -> Approved -> Applied.
- Needs a simple state machine.
Drafting the Implementation Steps (Mental Sandbox):
Structure of the Response:
- High-Level Architecture: Explain the components (Storage, Engine, API, UI).
- Data Model: Define what a "Policy" looks like.
- Core Implementation (Python):
PolicyDiffEngine: Compares JSON objects.
BlastRadiusAnalyzer: Resolves groups to users, checks resource impact.
PolicySimulator: The "What If" logic.
WorkflowManager: The approval logic.
- Example Usage: A script showing the flow from diff -> blast radius -> approval -> apply.
Self-Correction/Edge Cases:
- Wildcard matching: Real RBAC uses wildcards (e.g.,
s3:Get*). I should use a library or simple regex logic to handle this, or keep it simple with exact matches for the demo. Decision: Use fnmatch for wildcard support to make it realistic.
- Conditions: Conditions make RBAC complex (e.g., "only if IP is X"). Decision: Abstract this away in the code for brevity, but mention how the simulator handles it.
Detailed Design - The "Diff":
I need to canonicalize policies before diffing. Sort keys in JSON, sort lists. Otherwise, order matters too much.
Detailed Design - The "Blast Radius":
This is the hardest part computationally. In a real system (like AWS IAM), you need a graph.
For this code, I'll simulate a lookup:
- Policy targets Group
Developers.
- Blast radius checks: "Who is in Developers?" -> Returns User list.
- Blast radius checks: "What resources match
prod-*?" -> Returns Resource list.
Code Structure Plan:
models.py (dataclasses)
diff_engine.py
simulator.py
workflow.py
Let's merge this into a cohesive single script for the user to run.
Writing the prompt response:
- Introduction: Set the stage (Cloud-native, Security-first).
- The Architecture: Diagrammatic text.
- The Code: The meat of the answer.
- Explanation: Walk through the methods.
(Self-Correction during drafting code):
Make sure to handle "Deny" policies explicitly. Deny always overrides Allow.
The Diff should distinguish between Additions (Risk: Escalation) and Removals (Risk: Breakage).
Let's write the code.
Use deepdiff? No, standard library is better for portability, maybe json and set logic.
Need to canonicalize policy statements so {"A": 1, "B": 2} is same as {"B": 2, "A": 1}.
Blast Radius Logic:
Iterate proposed statements.
If Effect == Allow:
Find users matching Principal.
Find resources matching Resource.
Add to "Impact Set".
Simulation Logic:
Standard RBAC logic.
- Check explicit Denys.
- Check explicit Allows.
- Default Deny.
Approval Workflow:
Just a state machine wrapper.
Let's go.
This is a comprehensive design and implementation for a Granular RBAC Policy Diff Engine. This solution is architected as a Python library suitable for integration into a CI/CD pipeline or a standalone security tool.
Core Architecture
- The Policy Model: Uses a flexible JSON-like structure supporting Principals, Resources, Actions, and Conditions.
- The Diff Engine: Canonicalizes policies to detect logical changes (not just text diffs) and classifies them by risk.
- Blast Radius Analyzer: Cross-references policy changes with a user directory and resource inventory to determine who gets access to what.
- The Simulator: A context-aware Policy Decision Point (PDP) that runs "dry-run" requests against the proposed state.
- Workflow Manager: A state machine that enforces approvals based on risk severity.
Implementation
import json
import hashlib
import fnmatch
from dataclasses import dataclass, field
from typing import List, Dict, Set, Any, Optional
from enum import Enum
from datetime import datetime
# ==========================================
# 1. Data Models & Schema
# ==========================================
class RiskLevel(Enum):
LOW = 1 # e.g., Adding a non-critical resource
MEDIUM = 2 # e.g., Adding a user to a group
HIGH = 3 # e.g., Wildcard permissions, modifying roles
CRITICAL = 4 # e.g., Admin access, security group changes
@dataclass
class Statement:
effect: str # "Allow" or "Deny"
principals: List[str] # ["User:123", "Group:Admins"]
actions: List[str] # ["s3:GetObject", "iam:*"]
resources: List[str] # ["arn:aws:s3:::my-bucket/*"]
conditions: Dict = field(default_factory=dict)
def to_hashable(self) -> tuple:
# Helper to make JSON comparable
return (self.effect, tuple(sorted(self.principals)),
tuple(sorted(self.actions)), tuple(sorted(self.resources)),
json.dumps(self.conditions, sort_keys=True))
@dataclass
class RBACPolicy:
policy_id: str
version: str = "v1"
statements: List[Statement] = field(default_factory=list)
@classmethod
def from_json(cls, data: dict):
stmts = [Statement(**s) for s in data.get("statements", [])]
return cls(policy_id=data["policy_id"], version=data.get("version", "v1"), statements=stmts)
# ==========================================
# 2. The Diff Engine
# ==========================================
class PolicyDiffEngine:
"""
Calculates the logical difference between two policy states
and assigns a Risk Level to the change.
"""
def calculate_diff(self, old_policy: RBACPolicy, new_policy: RBACPolicy) -> dict:
old_stmts = {s.to_hashable() for s in old_policy.statements}
new_stmts = {s.to_hashable() for s in new_policy.statements}
added = new_stmts - old_stmts
removed = old_stmts - new_stmts
return {
"policy_id": old_policy.policy_id,
"added": [self._analyze_statement(s) for s in added],
"removed": [self._analyze_statement(s) for s in removed],
"is_change": bool(added or removed)
}
def _analyze_statement(self, stmt_tuple: tuple) -> dict:
"""
Analyzes a statement tuple to determine inherent risk.
"""
effect, principals, actions, resources, _ = stmt_tuple
risk = RiskLevel.LOW
# Heuristics for Risk Calculation
if effect == "Deny":
risk = RiskLevel.LOW # Explicit denies are usually safe corrections
elif "*" in actions or "*" in resources:
risk = RiskLevel.CRITICAL
elif "iam:" in " ".join(actions) or "admin" in " ".join(actions).lower():
risk = RiskLevel.HIGH
elif "Write" in " ".join(actions) or "Delete" in " ".join(actions):
risk = RiskLevel.MEDIUM
return {
"statement": stmt_tuple,
"risk_level": risk.name,
"risk_score": risk.value
}
# ==========================================
# 3. Blast Radius Preview
# ==========================================
class BlastRadiusAnalyzer:
"""
Simulates the impact of policy changes on the User/Resource graph.
Requires a mock directory state.
"""
def __init__(self, user_directory: Dict[str, List[str]], resource_inventory: List[str]):
# user_directory: Map of GroupName -> List of UserIDs
self.groups = user_directory
# resource_inventory: List of all known resource ARNs
self.resources = resource_inventory
def preview_blast_radius(self, diff_result: dict) -> dict:
impact_report = {
"users_affected": set(),
"resources_affected": set(),
"privilege_escalation_risk": False
}
for change in diff_result.get("added", []):
stmt = change["statement"]
_, principals, actions, resources, _ = stmt
# Resolve Principals
for p in principals:
if p.startswith("Group:"):
group_name = p.split(":")[1]
members = self.groups.get(group_name, [])
impact_report["users_affected"].update(members)
else:
impact_report["users_affected"].add(p)
# Resolve Resources (Simple wildcard matching)
for r_pattern in resources:
if r_pattern == "*":
impact_report["resources_affected"].update(self.resources)
else:
# basic glob matching simulation
matches = [res for res in self.resources if fnmatch.fnmatch(res, r_pattern)]
impact_report["resources_affected"].update(matches)
# Check for escalation
if change["risk_level"] in ["CRITICAL", "HIGH"]:
impact_report["privilege_escalation_risk"] = True
impact_report["users_affected"] = list(impact_report["users_affected"])
impact_report["resources_affected"] = list(impact_report["resources_affected"])
return impact_report
# ==========================================
# 4. Simulation Engine (What-If Analysis)
# ==========================================
class SimulationEngine:
"""
Evaluates hypothetical requests against the PROPOSED policy
to see if they would be allowed.
"""
def simulate_request(self, policy: RBACPolicy, principal: str, action: str, resource: str, context: dict = None) -> str:
decision = "DEFAULT_DENY"
for stmt in policy.statements:
if self._matches(stmt, principal, action, resource, context):
if stmt.effect == "Deny":
return "EXPLICIT_DENY"
if stmt.effect == "Allow":
decision = "ALLOW"
return decision
def _matches(self, stmt: Statement, principal: str, action: str, resource: str, context: dict) -> bool:
# Check Principal
p_match = False
for p in stmt.principals:
if p == principal: p_match = True
# Handle Group logic here if needed, usually expanded before policy eval
# Check Action
a_match = any(fnmatch.fnmatch(action, act) for act in stmt.actions)
# Check Resource
r_match = any(fnmatch.fnmatch(resource, res) for res in stmt.resources)
# Check Conditions (Simplified for demo)
c_match = True
if stmt.conditions:
# e.g., Condition: {"IpAddress": {"aws:SourceIp": "192.168.1.0/24"}}
# Logic to verify context IP matches CIDR block would go here
pass
return p_match and a_match and r_match and c_match
# ==========================================
# 5. Approval Workflow System
# ==========================================
class ApprovalWorkflow:
"""
State machine for managing the lifecycle of a policy change.
"""
def __init__(self):
self.pending_changes = {}
def submit_change_request(self, diff_result: dict, blast_radius: dict, author: str) -> str:
change_id = hashlib.md5(json.dumps(diff_result, default=str).encode()).hexdigest()[:8]
max_risk = max([0] + [c.get("risk_score", 0) for c in diff_result.get("added", [])])
requirements = self._determine_requirements(max_risk)
ticket = {
"id": change_id,
"status": "PENDING_APPROVAL",
"author": author,
"diff": diff_result,
"blast_radius": blast_radius,
"required_approvers": requirements["count"],
"current_approvals": [],
"created_at": datetime.utcnow().isoformat()
}
self.pending_changes[change_id] = ticket
return change_id
def _determine_requirements(self, risk_score: int) -> dict:
if risk_score >= 4: # CRITICAL
return {"count": 3, "auto_expire": True}
elif risk_score >= 3: # HIGH
return {"count": 2, "auto_expire": True}
elif risk_score >= 2: # MEDIUM
return {"count": 1, "auto_expire": False}
else:
return {"count": 0, "auto_expire": False} # Auto-merge
def approve(self, change_id: str, approver: str) -> str:
ticket = self.pending_changes.get(change_id)
if not ticket: return "ERROR: NOT_FOUND"
if approver in ticket["current_approvals"]:
return "ERROR: ALREADY_APPROVED"
ticket["current_approvals"].append(approver)
if len(ticket["current_approvals"]) >= ticket["required_approvers"]:
ticket["status"] = "APPROVED_READY_FOR_MERGE"
return f"APPROVED. Policy ready for merge."
return f"APPROVAL_RECORDED. {len(ticket['current_approvals'])}/{ticket['required_approvers']} approvals met."
# ==========================================
# 6. System Integration & Demo
# ==========================================
def main():
print("--- RBAC Policy Diff Engine Initialized ---")
# 1. Setup State
# Mock User Directory: Group "DevTeam" has User A and B
directory = {"DevTeam": ["User:A", "User:B"], "Admins": ["User:C"]}
inventory = ["arn:s3:data-bucket/file1", "arn:s3:data-bucket/file2", "arn:s3:secrets/credentials"]
# Current Policy
current_policy_data = {
"policy_id": "pol-123",
"statements": [
{"effect": "Allow", "principals": ["Group:DevTeam"], "actions": ["s3:GetObject"], "resources": ["arn:s3:data-bucket/*"]}
]
}
# Proposed Policy (Simulating a Developer adding too much access)
# Adding write access to the bucket, but accidentally targeting all resources (*)
proposed_policy_data = {
"policy_id": "pol-123",
"statements": [
{"effect": "Allow", "principals": ["Group:DevTeam"], "actions": ["s3:GetObject", "s3:PutObject"], "resources": ["arn:s3:data-bucket/*"]},
{"effect": "Allow", "principals": ["Group:DevTeam"], "actions": ["s3:DeleteObject"], "resources": ["*"]} # Risky!
]
}
current_policy = RBACPolicy.from_json(current_policy_data)
proposed_policy = RBACPolicy.from_json(proposed_policy_data)
# 2. Run Diff
engine = PolicyDiffEngine()
diff = engine.calculate_diff(current_policy, proposed_policy)
print(f"\n[DIFF] Changes detected: {len(diff['added'])} additions, {len(diff['removed'])} removals.")
for c in diff['added']:
print(f" - Risk: {c['risk_level']} | Action: {c['statement'][2]}")
# 3. Calculate Blast Radius
analyzer = BlastRadiusAnalyzer(directory, inventory)
blast = analyzer.preview_blast_radius(diff)
print(f"\n[BLAST RADIUS] Users Impacted: {blast['users_affected']}")
print(f"[BLAST RADIUS] Resources Impacted: {blast['resources_affected']}")
print(f"[BLAST RADIUS] Escalation Risk: {blast['privilege_escalation_risk']}")
# 4. Run Simulation (What-if)
sim = SimulationEngine()
# Test if User:A can delete secrets in the NEW policy
sim_result = sim.simulate_request(proposed_policy, "User:A", "s3:DeleteObject", "arn:s3:secrets/credentials")
print(f"\n[SIMULATION] User:A attempting to delete secrets: {sim_result}")
# 5. Workflow Management
workflow = ApprovalWorkflow()
change_id = workflow.submit_change_request(diff, blast, author="DevOps_Engineer")
print(f"\n[WORKFLOW] Submitted Change ID: {change_id}")
# Attempt approval
print(f"[WORKFLOW] Approving as Manager...")
msg = workflow.approve(change_id, "Manager_1")
print(f"[WORKFLOW] Status: {msg}")
if __name__ == "__main__":
main()
Technical Breakdown
1. Granular Diffing Logic
Standard text diffs (like Git diffs) are insufficient for RBAC because policy order doesn't matter, and logic overlap is complex.
- Canonicalization: We convert the policy statements into a set of tuples (
_hashable). This allows us to use Set Mathematics (Set A - Set B) to precisely identify additions and removals regardless of order.
- Risk Scoring: The
_analyze_statement method uses heuristics. If a change includes * (wildcards) or iam: permissions, the Risk Level automatically escalates to CRITICAL or HIGH.
2. Blast Radius Preview
This is the most critical feature for preventing "oops" moments.
- Principal Resolution: It expands groups. If a policy targets
Group:DevTeam, the engine looks up that group and flags every individual user (User:A, User:B) as "Impacted".
- Resource Expansion: It takes resource patterns (ARNs) like
arn:s3:data-bucket/* and checks them against the known inventory using fnmatch.
- Result: You get a concrete list: "This change will allow 50 users to delete 4,000 production files."
3. Simulation Engine
This acts as a sandbox.
- It accepts a
(Principal, Action, Resource, Context) tuple.
- It runs this request against the proposed policy logic but does not enforce it. It returns
ALLOW, DENY, or DEFAULT_DENY.
- Use Case: Before merging, a Security Engineer can run a simulation: "If I merge this, can
Intern_User access the Payroll database?"
4. Approval Workflow
The workflow ties everything together.
- Dynamic Gating: The
_determine_requirements method checks the Risk Score.
- Low risk (e.g., description update) might require 0 approvers (auto-merge).
- High risk (wildcards) requires 2+ approvers.
- State Machine: It tracks the ticket state, preventing changes from being applied until the approval count is met.
Deployment Architecture
In a production environment, this engine would sit within a "Policy-as-Code" pipeline:
- Repo: Policies are stored in Git (YAML/JSON).
- PR Creation: Developer modifies a policy JSON.
- CI Pipeline (Webhook):
- Instantiates
PolicyDiffEngine.
- Runs
BlastRadiusAnalyzer.
- Hard Block: If Risk is
CRITICAL, the CI pipeline fails immediately, blocking the PR merge.
- Bot Comment: The engine posts the Blast Radius report to the Pull Request comments (e.g., "Warning: This grants delete access to S3").
- External Approval: If risk rules are met, the
ApprovalWorkflow triggers a request in a ticketing system (Jira/ServiceNow).