Loading
Loading
IAM (Identity and Access Management) is the first line of defense in any cloud system.
Instead of assigning permissions to each person separately, create Roles and attach to them:
Don't use human accounts for automating processes. Create a Service Account with very limited permissions.
from dataclasses import dataclass, field
from typing import List, Dict, Set, Optional
from datetime import datetime, timedelta
import re
# ─── IAM Models ────────────────────────────────────────────
@dataclass
class Permission:
resource: str
actions: List[str]
conditions: Dict[str, str] = field(default_factory=dict)
def allows(self, action: str, resource: str) -> bool:
resource_match = (self.resource == "*" or resource.startswith(self.resource.rstrip("*")))
action_match = (action in self.actions or "*" in self.actions)
return resource_match and action_match
@dataclass
class Role:
name: str
description: str
permissions: List[Permission] = field(default_factory=list)
def can(self, action: str, resource: str) -> bool:
return any(p.allows(action, resource) for p in self.permissions)
@dataclass
class Principal:
name: str
kind: str # "user" | "service_account"
roles: List[str] = field(default_factory=list)
mfa: bool = False
last_used: Optional[str] = None
expires: Optional[str] = None
def is_expired(self) -> bool:
if not self.expires:
return False
return datetime.fromisoformat(self.expires) < datetime.now()
class IAMEngine:
def __init__(self):
self.roles: Dict[str, Role] = {}
self.principals:Dict[str, Principal] = {}
self._decisions: List[Dict] = []
def create_role(self, name: str, desc: str, *perms: Permission) -> Role:
r = Role(name, desc, list(perms))
self.roles[name] = r
print(f" 📋 Role: {name}")
return r
def create_principal(self, name: str, kind: str, roles: List[str],
mfa: bool = False, expires_days: int = 0) -> Principal:
exp = (datetime.now() + timedelta(days=expires_days)).isoformat() if expires_days else None
p = Principal(name, kind, roles, mfa, expires=exp)
self.principals[name] = p
icon = "🤖" if kind == "service_account" else "👤"
print(f" {icon} {kind}: {name} — roles: {roles}")
return p
def authorize(self, principal_name: str, action: str, resource: str) -> Dict:
p = self.principals.get(principal_name)
if not p:
dec = {"allow": False, "reason": "Principal غير موجود"}
self._decisions.append(dec)
return dec
if p.is_expired():
dec = {"allow": False, "reason": "الحساب منتهي الصلاحية"}
self._decisions.append(dec)
return dec
# Zero Trust: التحقق من MFA للعمليات الحساسة
sensitive_actions = ["delete", "iam:*", "admin:*"]
if any(a in action for a in ["delete", "iam", "admin"]) and not p.mfa:
dec = {"allow": False, "reason": "MFA مطلوب لهذه العملية"}
self._decisions.append(dec)
return dec
for role_name in p.roles:
role = self.roles.get(role_name)
if role and role.can(action, resource):
dec = {"allow": True, "reason": f"مسموح عبر Role: {role_name}"}
self._decisions.append(dec)
return dec
dec = {"allow": False, "reason": "لا توجد صلاحية مطابقة"}
self._decisions.append(dec)
return dec
def audit_report(self):
print(f"\n📊 تقرير IAM:")
print(f" Roles : {len(self.roles)}")
print(f" Principals : {len(self.principals)}")
problems = []
for name, p in self.principals.items():
if not p.mfa and p.kind == "user":
problems.append(f" ⚠️ {name}: MFA غير مُفعَّل")
if not p.expires and p.kind == "service_account":
problems.append(f" ⚠️ {name}: Service Account بدون تاريخ انتهاء")
if problems:
print(f"\n 🚨 مشاكل تحتاج تصحيح:")
for prob in problems:
print(prob)
else:
print(f"\n ✅ لا مشاكل")
# ─── تطبيق RBAC ────────────────────────────────────────────
print("🔐 IAM Best Practices — RBAC System:")
print("=" * 52)
iam = IAMEngine()
# إنشاء Roles
print("\n1️⃣ إنشاء Roles (RBAC):")
ai_dev_role = iam.create_role("ai-developer", "مطور AI",
Permission("bedrock:model/*", ["InvokeModel", "ListFoundationModels"]),
Permission("s3:ai-data-*", ["GetObject", "ListBucket"]),
)
data_sci_role = iam.create_role("data-scientist", "عالم بيانات",
Permission("s3:ml-data-*", ["GetObject", "PutObject", "ListBucket"]),
Permission("sagemaker:*", ["CreateTrainingJob", "DescribeTrainingJob"]),
)
mlops_role = iam.create_role("mlops-engineer", "مهندس MLOps",
Permission("sagemaker:endpoint/*",["CreateEndpoint", "DeleteEndpoint", "InvokeEndpoint"]),
Permission("ecr:*", ["GetDownloadUrlForLayer", "BatchGetImage"]),
Permission("iam:role/*", ["PassRole"]),
)
admin_role = iam.create_role("admin", "مدير (طوارئ فقط)",
Permission("*", ["*"]),
)
# إنشاء Principals
print(f"\n2️⃣ إنشاء Users و Service Accounts:")
iam.create_principal("ahmed@company.com", "user", ["ai-developer"], mfa=True)
iam.create_principal("sara@company.com", "user", ["data-scientist"], mfa=True)
iam.create_principal("lambda-ai-sa", "service_account", ["ai-developer"], expires_days=90)
iam.create_principal("ci-cd-sa", "service_account", ["mlops-engineer"], expires_days=365)
iam.create_principal("emergency-admin", "user", ["admin"], mfa=True)
iam.create_principal("old-key-no-mfa", "user", ["ai-developer"], mfa=False) # مشكلة!
# اختبار Authorization
print(f"\n3️⃣ اختبار القرارات الأمنية:")
checks = [
("ahmed@company.com", "InvokeModel", "bedrock:model/claude-3"),
("ahmed@company.com", "DeleteEndpoint", "sagemaker:endpoint/prod"), # MFA check
("sara@company.com", "PutObject", "s3:ml-data-training"),
("sara@company.com", "InvokeModel", "bedrock:model/titan"), # No permission
("lambda-ai-sa", "InvokeModel", "bedrock:model/haiku"),
("old-key-no-mfa", "delete", "s3:ml-data-production"),
]
for principal, action, resource in checks:
dec = iam.authorize(principal, action, resource)
icon = "✅" if dec["allow"] else "🚫"
p_s = principal.split("@")[0]
print(f" {icon} {p_s:<20} {action:<18} → {dec['reason']}")
# تقرير الأمان
iam.audit_report()