Skip to content

Authorization Models: RBAC, ABAC, ReBAC & Zero Trust ​

"Zero trust (ZT) provides a collection of concepts and ideas designed to minimize uncertainty in enforcing accurate, least privilege per-request access decisions in information systems and services in the face of a network viewed as compromised." — NIST SP 800-207، Zero Trust Architecture (Rose، Borchert، Mitchell، Connelly؛ اوت ۲۰۲۰)

خلاصه (Summary): مجوزدهی (Authorization) به این پرسش جواب می‌دهد: «آیا این کاربرِ احرازهویت‌شده همین حالا اجازه دارد این کار را روی این منبع انجام دهد؟» مدل‌ها فقط در اینکه به چه نگاه می‌کنند فرق دارند: ACL به فهرستِ یک شیء، RBAC به شغلِ کاربر، ABAC به ویژگی‌های کاربر و منبع و عمل و محیط، و ReBAC به گرافِ رابطه‌ها بین کاربر و شیءها. Zero Trust می‌گوید جواب باید برای هر درخواست محاسبه شود و هرگز از «کجا بودنِ درخواست در شبکه» نتیجه نشود. تمرکز (Focus): فرق authentication و authorization، نقش‌های XACML (PEP، PDP، PIP، PAP)، ACL، RBAC استاندارد NIST (نقش، سلسله‌مراتب، separation of duties، role explosion)، ABAC (NIST SP 800-162، XACML، ALFA، OPA Rego، Cedar)، ReBAC (Google Zanzibar، relation tuple، userset، rewrite rule، check، expand، list objects، zookie، OpenFGA، SpiceDB، Ory Keto، Permify)، capability و macaroon، جداسازی چندمستاجری (multi-tenancy) و row-level security، scope در برابر permission در OAuth، policy as code و تست سیاست، کش تصمیم و مسئلهٔ reverse index، audit log و explainability، Zero Trust (NIST SP 800-207، BeyondCorp، ZTNA، device posture، continuous verification) و در پایان Gate و Policy و spatie/laravel-permission در Laravel 13 کنار middleware در Go با OPA و Cedar و OpenFGA. هدف یادگیری (Learning goal): برای هر محصول بتوانید RBAC یا ABAC یا ReBAC یا ترکیبی را انتخاب کنید، نقطهٔ اعمال و نقطهٔ تصمیم را بگذارید، مستاجرها را از هم جدا نگه دارید، لغو دسترسی و فهرست‌کردن را در مقیاس درست کنید، سیاست‌ها را تست و ممیزی کنید و چکِ مجوز را در Laravel 13 و Go همراه با تست بنویسید.

این فصل در گروه Security است؛ بعد از Authentication (فراخواننده کیست)، JWT Deep Dive (توکنی که claim حمل می‌کند) و OAuth 2.0, OpenID Connect & SSO (دسترسی تفویض‌شده و scope)، و پیش از Cryptography in Practice، OWASP Top 10 (broken access control همان‌جا اولین مورد است) و Mutual TLS & Securing Service-to-Service Traffic (هویت workload که Zero Trust بین سرویس‌ها لازم دارد). مدل تهدید در Security Foundations است؛ سازوکار دیتابیسیِ نقش‌ها و row-level security در Database Security و Multi-Tenancy Strategies آمده. این صفحه صاحب تصمیم سطح سیستم است: کدام مدل، چک کجا اجرا شود، چقدر سریع باشد، چطور تست شود و چطور خراب شود.

نقشهٔ صفحه ​

اگر دنبال این هستیدبروید به
کل صفحه در چهار جدولهمه‌چیز در یک دقیقه
چرا مجوزدهی مسئلهٔ جداگانه‌ای استچرا وجود دارد
Ferraiolo و Kuhn، ABAC در NIST، Zanzibar، BeyondCorpاز کجا آمده
authentication در برابر authorizationAuthn در برابر authz
PEP، PDP، PIP، PAPنقش‌های XACML
فهرست‌های کنترل دسترسیACL
نقش و مجوزRBAC
سلسله‌مراتب، separation of duties، role explosionسلسله‌مراتب و قیدها
ویژگی و سیاستABAC
XACML، ALFA، Rego، Cedarزبان‌های سیاست
tuple، userset، rewrite ruleReBAC و Zanzibar
zookie و مسئلهٔ new enemyسازگاری
OpenFGA، SpiceDB، Keto، Permifyمحصولات ReBAC
capability و macaroonCapabilityها
tenant id در هر query، row-level securityچندمستاجری
scope در OAuth در برابر مجوز کاربرScope در برابر permission
policy as code و تست سیاستPolicy as code
کش تصمیم، batch check، فهرست‌کردنکارایی
audit log و explainabilityممیزی
اصول NIST SP 800-207Zero Trust
BeyondCorp، ZTNA، device posture، mTLSZero Trust در عمل
knobهای دقیق و کدهای خطاسازوکار
کدGo، Laravel، SQL
شکست‌های کلاسیک و راه‌حلحل مسئله‌های کلاسیک
کدام مدل برای کدام محصولانتخاب
از مونولیت تا سیستم توزیع‌شدهدر معماری
عددهای آزمایشگاهآزمایشگاه
باور غلط، چکیده، خودآزمایی، واژه‌هابدفهمی‌ها، برگهٔ یادسپار، خودآزمایی، واژه‌نامه

همه‌چیز در یک دقیقه ​

احراز هویت و مجوزدهی دو پرسش جدا هستند.

پرسشنامسازوکار معمولوضعیت شکستمعنی شکست
تو کیستی؟احراز هویت (Authentication، authn)رمز، MFA، کوکی نشست، JWT، گواهی mTLS401 Unauthorizedنمی‌دانم کیستی
چه کاری مجازی؟مجوزدهی (Authorization، authz)نقش، ویژگی، رابطه، سیاست403 Forbidden (یا 404)می‌شناسمت؛ جواب نه است
کدام برنامه از طرف تو عمل کند؟تفویض (Delegation)scopeهای OAuth 2.0، رضایت403 insufficient_scopeبه آن client داده نشده

چهار مدل، هر کدام در یک سطر.

مدلتصمیم به چه نگاه می‌کندپرسش نمونهنقطهٔ قوتنقطهٔ ضعفمحصولات
ACLیک شیء و فهرست کاربرانشآیا آنا در فهرست این فایل است؟ساده، روی هر شیءبا زیاد شدن شیءها نمی‌خواند؛ ارث‌بری نداردمجوزهای POSIX، ACLهای S3، NTFS
RBACنقش‌های کاربرآیا آنا نقشی با invoice:approve دارد؟ممیزی آسان، منطبق با شغلrole explosion؛ کور به شیء و زمینهspatie/laravel-permission، نقش‌های Keycloak، گروه‌های AWS IAM
ABACویژگی‌های کاربر، منبع، عمل، محیطهمان بخش، ساعت کاری، دستگاه مدیریت‌شده؟ریزدانه، سیاست مرکزیجواب «چه کسی X را می‌بیند؟» و اشکال‌زدایی سختOPA، Cedar، XACML، شرط‌های AWS IAM
ReBACمسیرها در گراف رابطه‌هاآیا آنا ویرایشگر پوشه‌ای است که این سند در آن است؟اشتراک‌گذاری، ارث‌بری، تو در توبه store و سازگاری و reverse index نیاز داردZanzibar، OpenFGA، SpiceDB، Ory Keto، Permify

نقش‌های XACML (در NIST SP 800-162 و SP 800-207 هم می‌آیند).

نقشمخففکاردر عمل کجاست
Policy Enforcement PointPEPدرخواست را می‌گیرد، می‌پرسد، جواب را اجرا می‌کندAPI gateway، middleware، Gate و can middleware در Laravel، فیلتر Envoy
Policy Decision PointPDPسیاست‌ها را روی ویژگی‌ها ارزیابی و permit یا deny برمی‌گرداندOPA، Cedar، SpiceDB، OpenFGA، کلاس Policy در Laravel
Policy Information PointPIPویژگی و رابطه‌ای که PDP ندارد را می‌دهدسرویس کاربر، دیتابیس HR، موجودی دستگاه‌ها، tuple store
Policy Administration PointPAPجایی که سیاست نوشته، نسخه‌دار و منتشر می‌شودمخزن Git به‌علاوهٔ CI، کنسول مدیریت

Zero Trust در یک جدول.

فرض قدیمیقاعدهٔ Zero Trustچه می‌سازید
داخل شبکه یعنی مورد اعتمادموقعیت شبکه به‌تنهایی اعتماد نمی‌آوردPEP جلوی هر منبع، mTLS بین سرویس‌ها
یک بار ورود، گردش آزاددسترسی per-session داده و دوباره ارزیابی می‌شودنشست کوتاه، step-up، continuous verification
هویت کافی استوضعیت دستگاه و زمینه هم حساب استموجودی دستگاه، بررسی posture، سیگنال ریسک
نقش‌های پهن اشکالی نداردleast privilege در هر درخواستمجوز باریک، اعطای just-in-time

چرا وجود دارد ​

هر endpoint در یک سیستم واقعی یک تصمیم می‌گیرد: آیا این فراخواننده می‌تواند فاکتور ۴۷۱۱ را بخواند؟ سیستمِ بدون مدلِ آگاهانه جواب را با ifهای پراکنده در هر controller می‌دهد. این ifها از هم دور می‌شوند، endpoint جدید یکی را فراموش می‌کند و نتیجه همان اولین ردیف OWASP Top 10 است: broken access control. برگهٔ Authorization Cheat Sheet از OWASP خط پایه را در دو قاعده می‌گوید: "Enforce Least Privileges" و "Deny by Default" ("The application must always make a decision, whether implicitly or explicitly, to either deny or permit the requested access").

سمت سادهسمت غنیچیزی که معامله می‌کنید
ستون بولین is_adminموتور سیاست با زبان خودشممیزی‌پذیری و دقت در برابر وزن عملیاتی
چک در controllerچک در PDP مرکزییک جا برای استدلال در برابر یک hop شبکه و وابستگی تازه
نقش روی کاربررابطه روی شیء«آنا چه می‌تواند» آسان در برابر «چه کسی این سند را می‌بیند» آسان
اعطای ایستاقاعدهٔ پویا بر پایهٔ ویژگیمرور قابل‌پیش‌بینی در برابر انعطاف (و غافلگیری)
شک کردی؟ رد کنشک کردی؟ اجازه بدهامنیت در برابر دسترس‌پذیری وقتی PDP از کار افتاده

تصویر روزمره. ساختمانی که پشت هر در کارت‌خوان دارد. RBAC رنگ کارت شماست (کارمند، نظافت، مهمان). ABAC قاعده‌هایی از زمینه اضافه می‌کند: فقط در ساعت کاری، فقط اگر همراه دارید. ReBAC می‌گوید «کسی که این اتاق جلسه را رزرو کرده می‌تواند مهمان بیاورد و مهمان‌ها از تختهٔ همان اتاق استفاده کنند». Zero Trust نگهبان دروازهٔ ورودی را برمی‌دارد که همه را رد می‌کرد: هر در، هر بار، دوباره چک می‌کند.

سه بدفهمی رایج، از همین اول ​

  1. «لاگین داریم، پس مجوزدهی داریم.» نشستِ معتبر فقط هویت را ثابت می‌کند. رایج‌ترین رخنهٔ واقعی این است که کاربرِ واردشده یک id را در URL عوض می‌کند (insecure direct object reference، broken object level authorization).
  2. «RBAC قدیمی است و ABAC و ReBAC جایش را می‌گیرند.» لایه‌لایه می‌شوند. تقریباً هر محصول یک چک نقشِ درشت نگه می‌دارد (آیا این فرد اصلاً به ماژول صورت‌حساب دسترسی دارد) و بعد یک قاعدهٔ سطح شیء (آیا این فاکتور را باز کند).
  3. «Zero Trust محصولی است که می‌خرید.» NIST SP 800-207 آن را "a collection of concepts and ideas" می‌نامد و ZTA را "an enterprise's cybersecurity plan". محصولات (دروازه‌های ZTNA، proxyهای آگاه از هویت) بخش‌هایی از آن را پیاده می‌کنند.

از کجا آمده ​

سالرویدادمنبع
۱۹۹۲David Ferraiolo و Rick Kuhn کنترل دسترسی مبتنی بر نقش را صوری کردندصفحهٔ پروژهٔ NIST RBAC
۲۰۰۴مدل RBAC از NIST به‌عنوان ANSI/INCITS 359-2004 پذیرفته شد (۱۱ فوریه ۲۰۰۴)؛ در ۲۰۱۲ به INCITS 359-2012 بازبینی شدصفحهٔ پروژهٔ NIST RBAC
۲۰۱۴NIST SP 800-162 مدل ABAC را تعریف می‌کند (ژانویه ۲۰۱۴؛ به‌روزرسانی تا ۲ اوت ۲۰۱۹)NIST SP 800-162
۲۰۱۴BeyondCorp: "A New Approach to Enterprise Security" (Ward و Beyer، ;login: جلد ۳۹ شمارهٔ ۶)؛ macaroon (NDSS 2014)research.google
۲۰۱۶BeyondCorp: "Design to Deployment at Google" (;login: 41)، سطح‌های پویای اعتماد برای دستگاه‌هاresearch.google
۲۰۱۹Zanzibar: Google's Consistent, Global Authorization System (USENIX ATC 2019)research.google
۲۰۲۰NIST SP 800-207 Zero Trust Architecture (اوت ۲۰۲۰)NIST SP 800-207

منابع اصلی دقیقاً چه می‌گویند:

  • صفحهٔ RBAC در NIST می‌گوید RBAC "has become the predominant model for advanced access control because it reduces this cost" (هزینهٔ مدیریت امنیت در شبکه‌های بزرگ).
  • NIST SP 800-162 مدل ABAC را این‌طور تعریف می‌کند: "a logical access control methodology where authorization to perform a set of operations is determined by evaluating attributes associated with the subject, object, requested operations, and, in some cases, environment conditions against policy, rules, or relationships". هزینهٔ RBAC خالص را هم نام می‌برد: نقش‌های موردی که به آنچه معمولاً "role explosion" خوانده می‌شود می‌رسند.
  • مقالهٔ Zanzibar گزارش می‌دهد "trillions of access control lists and millions of authorization requests per second"، با "95th-percentile latency of less than 10 milliseconds and availability of greater than 99.999% over 3 years of production use".
  • چکیدهٔ BeyondCorp: امنیت پیرامونی "problematic because, when that perimeter is breached, an attacker has relatively easy access to a company's privileged intranet".
  • جانشین‌های متن‌باز Zanzibar: SpiceDB (AuthZed) می‌گوید مقاله الهام‌بخشش بوده؛ Ory Keto خود را "the first open-source implementation" طراحی Zanzibar می‌نامد؛ Permify می‌گوید "inspired by Google's consistent, global authorization system"؛ OpenFGA پروژهٔ CNCF با زبان مدل‌سازی به سبک Zanzibar است.

فهرست مفاهیم ​

هر بلوک همین ترتیب را دارد: به زبان ساده، بدفهمی رایج، تعریف، خط زمانی، سناریوهای واقعی، اینکه محصولات چطور فراهمش می‌کنند، و راه‌حل.

احراز هویت (Authentication) در برابر مجوزدهی (Authorization) حیاتی ​

به زبان ساده: احراز هویت نشان‌دادن کارت شناسایی دم در است؛ مجوزدهی فهرستی است که می‌گوید آن کارت کدام اتاق‌ها را باز می‌کند.

بدفهمی رایج: «اگر JWT معتبر است درخواست مجاز است.» امضای معتبر فقط ثابت می‌کند چه کسی claimها را صادر کرده و دست‌کاری نشده‌اند. اینکه این کاربر اجازهٔ دست‌زدن به این شیء را دارد تصمیم جداست، و claimهایی مثل role: admin داخل توکن به اندازهٔ خودِ توکن کهنه‌اند (نگاه کنید به JWT Deep Dive).

تعریف: احراز هویت سوژه (کاربر یا workload) را مشخص می‌کند و هویتی با ویژگی‌ها می‌دهد؛ مجوزدهی تابع decide(subject, action, resource, context) است که بعد از احراز هویت و پیش از انجام کار permit یا deny برمی‌گرداند.

text
     Actor        Step                                     Result
1    client       GET /invoices/4711 with session cookie
2    PEP          authenticate: cookie -> user ana         401 if missing or invalid
3    PEP          build request (ana, read, invoice:4711)
4    PDP          evaluate policies with attributes        permit or deny, with reason
5    PEP          deny -> 403 (or 404); permit -> handler
6    PEP          write audit record (who, what, decision, policy id)

سناریوهای واقعی: کاربر اپ موبایل invoices/4711 را به invoices/4712 تغییر می‌دهد (چک شیء لازم است نه چک لاگین)؛ پشتیبان می‌تواند هر تیکت را بخواند ولی نه export کند (مجوز، نه هویت)؛ حساب سرویسِ billing می‌تواند فاکتور بخواند ولی کاربر نه (مجوزدهی workload)؛ یک client از OAuth فقط پروفایل را می‌خواند چون کاربر فقط همان scope را داده.

وضعیتوضعیت HTTPچرا
بدون اعتبارنامه یا اعتبارنامهٔ بد401احراز هویت شکست خورده؛ WWW-Authenticate بفرستید
کاربر شناخته، مجاز نیست403مجوزدهی شکست خورده
کاربر شناخته، وجود منبع نباید فاش شود404وجود را پنهان می‌کند (Response::denyAsNotFound() در Laravel)
سرویس سیاست در دسترس نیست503 (fail closed)هرگز خطا را به allow تبدیل نکنید

راه‌حل / نحوهٔ استفاده: دو گام را در دو لایه نگه دارید (middleware احراز هویت، بعد middleware یا Policy مجوزدهی)؛ هرگز مجوز را از داده‌ای که client می‌فرستد نخوانید. کد در Go و Laravel است.

نقش‌های XACML: PEP، PDP، PIP، PAP حیاتی ​

به زبان ساده: یک قطعه می‌پرسد، یک قطعه تصمیم می‌گیرد، یک قطعه واقعیت‌ها را می‌رساند، یک قطعه دفتر قانون را نگه می‌دارد.

بدفهمی رایج: «موتور سیاست درخواست‌ها را مسدود می‌کند.» PDP فقط جواب می‌دهد. PEP مسدود می‌کند. اگر PEP صدا زدنش را فراموش کند یا خطایش را نادیده بگیرد، هیچ چیز محافظت نمی‌شود.

تعریف: این نقش‌ها از معماری مرجع XACML می‌آیند که NIST SP 800-162 آن را چنین خلاصه می‌کند: "Policy Decision Points (PDPs), Policy Enforcement Points (PEPs), Policy Administration Points (PAPs), and Policy Information Points (PIPs)". NIST SP 800-207 همین ایده را دوباره به کار می‌برد: policy engine (PE) و policy administrator (PA) با هم PDP را می‌سازند و PEP جلوی منبع می‌نشیند.

Clientuser, servicePEPpolicy enforcementgateway, middleware, GatePDPpolicy decisionOPA, Cedar, SpiceDB, OpenFGAPIPpolicy informationuser store, HR, device posture, tuplesPAPpolicy administrationResourceAPI, row, fileAudit logwho, what, decision, policyrequest / decisionallowed requests onlypoliciesattributes
text
     PEP                  PDP                      PIP                   PAP
1    request arrives
2    ask(subject,action,resource,env) ->
3                         need department of ana -> 
4                                                  <- department=finance
5                         evaluate policies loaded from PAP bundle
6    <- decision(permit, policy=dept-read, obligations)
7    enforce; log

سناریوهای واقعی: ext_authz در Envoy، OPA را صدا می‌زند (sidecar همان PEP است)؛ gatewayای مثل Kong یا NGINX سرویس auth را صدا می‌زند؛ middleware can:update,document در Laravel همان PEP است و کلاس DocumentPolicy همان PDP؛ دیتابیس با row-level security هم PEP است هم PDP.

جایگذاریPEPPDPتأخیرنکته
کتابخانهٔ درون‌فرایندیکد شمادرون‌فرایندی (کتابخانهٔ Cedar، Policy در Laravel، ارزیاب Go)میکروثانیهسیاست همراه باینری می‌آید
Sidecarبرنامه یا EnvoyOPA روی localhostزیر میلی‌ثانیه تا چند msbundleها را PAP می‌فرستد
سرویس مرکزیبرنامهSpiceDB، OpenFGA، سرویس authیک رفت‌وبرگشت شبکهیک منبع حقیقت برای رابطه‌ها
GatewayGatewayافزونهٔ gateway یا OPAدر هر درخواست، در لبهفقط چک‌های درشت؛ سرویس باز هم شیء را چک می‌کند

راه‌حل / نحوهٔ استفاده: یک نوع Request و یک نوع Decision تعریف کنید (نگاه کنید به authz.go) تا PDP عوض شود و handlerها دست نخورند؛ PEP را fail closed بسازید.

فهرست‌های کنترل دسترسی (ACL) مهم ​

به زبان ساده: هر شیء فهرست خودش را دارد که می‌گوید چه کسی چه کاری با آن می‌تواند بکند.

بدفهمی رایج: «ACL منسوخ است.» اشتراک‌گذاری سند («هر کسی با لینک»، «آنا می‌تواند ویرایش کند») همان ACL است؛ اسم Zanzibar هم عملاً یک سیستم ACL است. آنچه عوض شده نحوهٔ ذخیره و ارث‌بری ACL است.

تعریف: ACL فهرستی از ورودی‌های (کاربر، مجوز) است که به شیء وصل شده. چک یک شیء ارزان است؛ پرسش «آنا به چه چیزهایی دسترسی دارد» اسکن همهٔ شیءها می‌خواهد، که دوباره همان مسئلهٔ reverse index است.

text
     object            ACL entries
1    /reports/q3.pdf   ana:read   bob:read,write   group:finance:read
2    check(ana, read, /reports/q3.pdf)  -> scan list -> found -> permit
3    check(eve, read, /reports/q3.pdf)  -> scan list -> not found -> deny

سناریوهای واقعی: بیت‌های mode فایل در لینوکس و ACLهای POSIX؛ ACLهای bucket و object در S3؛ DACLهای NTFS در ویندوز؛ ACL در Redis (ACL SETUSER) برای دستورها و کلیدها؛ جدول shared_with برای سند.

سیستمریزدانگی ACLارث‌بری
فایل‌سیستم POSIXمالک، گروه، دیگران، به‌علاوهٔ ورودی‌های ACL گستردهACLهای پیش‌فرض روی دایرکتوری
Amazon S3برای هر bucket و هر objectبین شیءها ندارد
Redis 6+ ACLبرای هر کاربر: دستورها، الگوی کلیدها، کانال‌هاندارد
اشتراک‌گذاری به سبک Google Driveبرای هر فایل و پوشهاز پوشه به فرزندان (این همان ReBAC است)

راه‌حل / نحوهٔ استفاده: جدول shared_with(resource_id, subject, permission) شروع مشروعی است؛ وقتی گروه و پوشه اضافه می‌کنید دارید ReBAC می‌سازید و باید آن را به‌صورت tuple مدل کنید (نگاه کنید به SQL).

RBAC: کاربر، نقش، مجوز، نشست حیاتی ​

به زبان ساده: به آدم‌ها عنوان شغلی (نقش) می‌دهید، عنوان مجوزها را حمل می‌کند، پس به‌جای آدم‌ها عنوان‌ها را مدیریت می‌کنید.

بدفهمی رایج: «نقش همان مجوز است.» مجوز (Permission) یک عمل روی یک نوع شیء است (invoice:approve). نقش (Role) کیسه‌ای از مجوزهاست که با یک شغل جور درمی‌آید. hasRole('admin') در کد برنامه کد را به چارت سازمانی گره می‌زند؛ مجوز را چک کنید و بگذارید نقش‌ها گروهشان کنند (مستندات spatie/laravel-permission هم همین را می‌گوید).

تعریف (NIST RBAC): مدل مرجع کاربر، نقش، مجوز (عملی روی شیء)، اعطای کاربر (UA)، اعطای مجوز (PA)، نشست (کاربر زیرمجموعه‌ای از نقش‌های اعطاشده را فعال می‌کند) و در صورت نیاز سلسله‌مراتب و قید دارد. این مدل ANSI/INCITS 359-2004 شد. کاربر می‌تواند کاری بکند وقتی یکی از نقش‌های فعالش آن مجوز را داشته باشد.

text
     Step                              State
1    admin: grant clerk -> invoice:create, invoice:read
2    admin: assign ana -> clerk
3    ana logs in, session activates {clerk}
4    ana: POST /invoices       -> role clerk has invoice:create -> permit
5    ana: POST /invoices/9/approve -> no active role has invoice:approve -> deny

سناریوهای واقعی: برنامهٔ back-office با admin و support و finance؛ Role و RoleBinding در Kubernetes؛ گروه‌ها و roleهای AWS IAM؛ نقش‌های realm و client در Keycloak؛ برنامهٔ Laravel با spatie/laravel-permission.

محصول«نقش» چیستقالب مجوزنکته
spatie/laravel-permissionردیف در roles که به مجوزها وصل استرشتهٔ آزاد (edit articles)مجوزها را در Gate ثبت می‌کند؛ نسخه‌های 7 و 8 لاراول 12 و 13 را پشتیبانی می‌کنند
Kubernetes RBACRole یا ClusterRole از قاعده‌هافعل روی منبعفقط افزایشی؛ deny ندارد
AWS IAMroleای که principal می‌پذیردرشتهٔ Action در سیاست‌هاسیاست‌ها شرط (ABAC) و deny صریح هم دارند
Keycloakrealm role، client role، composite roleنام نقشcomposite roleها همان سلسله‌مراتب‌اند

راه‌حل / نحوهٔ استفاده: نقش و مجوز را در جدول نگه دارید (نگاه کنید به SQL)، مجوز را در کد چک کنید، از طریق نقش اعطا کنید و تعداد نقش‌ها را کم نگه دارید (بلوک بعد). کد: Laravel و ارزیاب خالص در Go.

سلسله‌مراتب نقش، separation of duties، role explosion حیاتی ​

به زبان ساده: نقش ارشد آنچه نقش پایین‌تر می‌تواند را به ارث می‌برد؛ بعضی جفت نقش‌ها هرگز نباید در یک نفر جمع شوند؛ و اگر برای هر مورد نقش بسازید نقش‌ها از آدم‌ها بیشتر می‌شوند.

بدفهمی رایج: «نقش بیشتر یعنی کنترل ریزتر.» از جایی به بعد یعنی هیچ‌کس نمی‌تواند سیستم را ممیزی کند. ترکیب بخش x منطقه x سطح (۶ x ۴ x ۳) همین حالا ۷۲ نقش می‌سازد؛ NIST SP 800-162 نتیجه را "role explosion" می‌نامد.

تعریف: سلسله‌مراتب نقش یک ترتیب جزئی است که نقش ارشد مجوزهای نقش پایین را به ارث می‌برد. Static separation of duties (SSD) اجازه نمی‌دهد کاربری اصلاً نقش‌های متضاد داشته باشد (مثلاً clerk و approver). Dynamic separation of duties (DSD) هر دو اعطا را اجازه می‌دهد ولی فعال‌کردن هر دو در یک نشست را ممنوع می‌کند. هر دو قید یعنی «هیچ کاربری (نشستی) نباید N نقش یا بیشتر از این مجموعه داشته باشد».

text
     Step                                      Outcome
1    constraint SSD{clerk, approver, N=2}
2    assign bob -> clerk                       ok
3    assign bob -> approver                    refused: ErrSSD (bob would hold 2 of 2)
4    constraint DSD{teller, auditor, N=2}
5    assign eve -> teller, auditor             ok (assignment allowed under DSD)
6    session(eve) activates {teller, auditor}  refused: ErrDSD
7    session(eve) activates {auditor}          ok

سناریوهای واقعی: اصل چهار چشم برای پرداخت (سازنده نمی‌تواند تأیید کند)، معامله‌گری که نباید مسئول ریسک هم باشد، باجه‌داری که در روزی دیگر ممیز است، سلسله‌مراتب admin > manager > employee، نقش break-glass دو ساعته (expires_at).

تکنیکچطور با role explosion مقابله می‌کندهزینه
سلسله‌مراتب نقشنقش ارشد ارث می‌برد؛ تعریف کمترچرخه باید رد شود؛ ممیزی closure می‌خواهد
چک بر پایهٔ مجوزکد هرگز نام نقش نمی‌بردفهرست مجوزها لازم است
نقش پارامتری (نقش به‌علاوهٔ scope، مثل approver@region=EU)یک نقش، چند scopeبه سمت ABAC می‌رود
لایهٔ ویژگی (ABAC)به‌جای نقش برای هر ترکیب ویژگیبازبینی سیاست ضروری می‌شود
لایهٔ رابطه (ReBAC)به‌جای نقش برای هر پروژه یا سندبه store رابطه نیاز دارد

راه‌حل / نحوهٔ استفاده: مدل درون‌فرایندی در Go (بستهٔ rbac) closure سلسله‌مراتب، SSD هنگام اعطا و DSD هنگام شروع نشست را با تست نشان می‌دهد.

ABAC: ویژگی و سیاست حیاتی ​

به زبان ساده: به‌جای «آنا مدیر است»، قاعده می‌گوید «اجازه بده اگر بخش کاربر با بخش سند یکی است، روز کاری است و دستگاه مدیریت‌شده است».

بدفهمی رایج: «ABAC یعنی نقش نداریم.» نقش فقط یکی از ویژگی‌های کاربر است. ABAC تعمیم RBAC است و NIST SP 800-162 می‌گوید ABAC "avoids the need for capabilities (operation/object pairs) to be directly assigned to subject requesters or to their roles or groups".

تعریف (NIST SP 800-162): دسترسی با ارزیابی ویژگی‌های سوژه، شیء (منبع)، عمل درخواستی و در بعضی موارد محیط در برابر سیاست تصمیم‌گیری می‌شود. ویژگی‌ها جفت نام و مقدارند. سیاست‌ها قاعده‌هایی روی ویژگی‌اند. ویژگی‌های محیطی شامل زمان، مکان، سطح تهدید و وضعیت دستگاه است.

text
     Attribute group   Example attributes
1    subject           id, department, clearance, tenant_id, roles, mfa_level
2    resource          owner_id, classification, tenant_id, department, status
3    action            read, edit, delete, approve
4    environment       hour, ip range, device_managed, risk_score
     rule: permit read if subject.department == resource.department and 8 <= hour < 18
     rule: forbid if subject.tenant_id != resource.tenant_id           (forbid wins)

سناریوهای واقعی: «پیمانکارها فقط سندهای غیرمحرمانه را از دستگاه مدیریت‌شده بخوانند»؛ «پزشک فقط پرونده بیماران بخش خودش را بخواند»؛ «پرداخت بالای ۱۰٬۰۰۰ تأییدکنندهٔ با سقف بالاتر می‌خواهد»؛ بلوک‌های Condition در AWS IAM و دسترسی بر پایهٔ tag (aws:PrincipalTag برابر aws:ResourceTag)؛ سیاست‌های admission در Kubernetes.

جنبهRBACABAC
حقیقت کجاستجدول‌های کاربر-نقش و نقش-مجوزویژگی‌ها در چند سیستم، به‌علاوهٔ سیاست‌ها
«آنا چه می‌تواند؟»آسان: اجتماع نقش‌هاسخت: همهٔ منابع را ارزیابی کنید
«چه کسی این را می‌خواند؟»آسان: نقش‌های دارای مجوزسخت: همهٔ کاربران را ارزیابی کنید
تغییر یک قاعدهیک نقش را ویرایش کنیدسیاست را ویرایش و هر چه را لمس می‌کند دوباره تست کنید
شکست معمولrole explosionویژگی غلط یا کهنه، اثر متقابل غافلگیرکنندهٔ قاعده‌ها

راه‌حل / نحوهٔ استفاده: منبع‌های ویژگی (PIP) را کم و سریع نگه دارید، سیاست را در Git نسخه‌دار کنید، با deny-overrides و default deny ترکیب کنید؛ بستهٔ abac در Go این را در ۵۰ خط انجام می‌دهد و DocumentPolicy در Laravel همان ABAC به PHP است.

زبان‌های سیاست: XACML، ALFA، Rego، Cedar مهم ​

به زبان ساده: زبان سیاست اجازه می‌دهد قاعده‌ها را به‌صورت داده یا کدی بنویسید که PDP بتواند اجرا کند، به‌جای ifهای پراکنده در controllerها.

بدفهمی رایج: «زبان سیاست یک قابلیت امنیتی است.» راهی است برای اینکه قاعده‌ها قابل‌بازبینی، قابل‌تست و قابل‌تحلیل شوند. سیاست بد در Rego هم به اندازهٔ PHP غلط است.

تعریف: XACML استاندارد XML از OASIS با معماری PEP/PDP/PIP/PAP، target و rule و الگوریتم‌های ترکیب است؛ ALFA (Abbreviated Language for Authorization) نحو فشرده‌ای است که به XACML کامپایل می‌شود. OPA (Open Policy Agent) موتور سیاست عمومی است با زبان Rego؛ مستندات OPA می‌گویند "accepts arbitrary structured data as input" و "domain-agnostic" است. Cedar زبانی از AWS است: سیاست‌ها اثر (permit یا forbid)، scope (principal، action، resource) و شرط‌های اختیاری دارند و قاعدهٔ ترکیب این است: اگر دست‌کم یک permit بخورد و هیچ forbid نخورد اجازه، وگرنه رد.

زبانسبکپیش‌فرضقاعدهٔ تعارضتحلیل‌پذیرکجا استفاده می‌شود
XACML 3.0XML، target و ruleکاربرد نداردالگوریتم‌های ترکیب (deny-overrides، permit-overrides، first-applicable)محدودمجموعه‌های IAM سازمانی
ALFAمتن فشرده روی XACMLمثل XACMLمثل XACMLمحدودابزار Axiomatics
Rego (OPA)قاعده‌های شبه‌Datalog روی JSONundefined مگر default allow := falseخودتان می‌نویسید (مجموعهٔ deny، count(deny) == 0)با تستKubernetes Gatekeeper، Envoy، چک‌های Terraform، APIها
Cedarpermit و forbid اعلانیDenyforbid بر permit غلبه دارداعتبارسنجی با schema، تحلیل صوریAmazon Verified Permissions، cedar-go
rego
package authz

import rego.v1

default allow := false

# Deny wins: a tenant mismatch can never be overridden by a permit rule.
deny contains "cross-tenant" if input.SubjectTenant != input.Resource.Tenant

allow if {
	count(deny) == 0
	input.Action == "read"
	input.SubjectAttrs.department == input.Resource.Attrs.department
	input.Env.hour >= "08"
	input.Env.hour < "18"
}

allow if {
	count(deny) == 0
	input.Action == "edit"
	input.Resource.Attrs.owner == input.Subject
}
cedar
// Role-like permit: scope only, no conditions.
permit (principal in Group::"editors", action in [Action::"read", Action::"edit"], resource is Document);

// Attribute-based permit with a condition.
permit (principal, action == Action::"read", resource is Document)
when { principal.department == resource.department && resource.classification != "confidential" };

// Forbid always wins over every permit.
forbid (principal, action, resource)
unless { principal.tenant == resource.tenant };
text
     Request: ana, read, doc:1 (finance), hour 22
1    Rego: allow rules need hour < 18 -> none matches -> default allow := false -> deny
2    Cedar: permit "dept-read" matches; forbid "tenant-wall" does not -> allow
       (the after-hours rule must be a `when` clause; scope alone cannot see the clock)

راه‌حل / نحوهٔ استفاده: برای هر لایه یک زبان انتخاب کنید، پیش‌فرض را deny بنویسید، قاعدهٔ تعارض را صریح کنید (forbid می‌برد) و تست کنید (نگاه کنید به policy as code). REST Data API در OPA وقتی قاعدهٔ پرسیده‌شده undefined است HTTP 200 بدون ویژگی result برمی‌گرداند، پس client باید نبودِ result را deny بشمارد، همان‌طور که decider با نام httpguard.OPA در Go می‌کند.

ReBAC و Zanzibar: relation tuple، userset، rewrite rule حیاتی ​

به زبان ساده: مجوز رابطه‌ها را دنبال می‌کند: می‌توانید سند را باز کنید اگر عضو گروهی هستید که بیننده (viewer) پوشه‌ای است که سند در آن قرار دارد.

بدفهمی رایج: «ReBAC قابلیت گراف دیتابیس است.» مدل گراف است، اما Zanzibar relation tupleهای تخت را در یک دیتابیس معمولی ذخیره می‌کند (Spanner در گوگل) و جواب را با پیمودن آن‌ها زیر rewrite ruleها حساب می‌کند.

تعریف (مقالهٔ Zanzibar): relation tuple شکل متنی object#relation@user دارد، که subject یا شناسهٔ کاربر است یا userset به شکل object#relation. جدول ۱ مقاله می‌گوید: doc:readme#owner@10 (کاربر ۱۰ مالک سند است)، group:eng#member@11، doc:readme#viewer@group:eng#member (اعضای گروه eng بینندهٔ سندند)، doc:readme#parent@folder:A#... (سند در پوشهٔ A است). configuration هر namespace برای هر relation یک userset rewrite rule تعریف می‌کند: this (tupleهای مستقیم)، computed_userset (relation دیگر روی همان شیء)، tuple_to_userset (یک tuple مثل parent را دنبال کن و آنجا relation بپرس)، که با union، intersection یا exclusion ترکیب می‌شوند. APIها Check، Read، Write، Watch و Expand هستند؛ Expand درخت userset مؤثر را برمی‌گرداند و Leopard سیستم indexی است که مجموعه‌های بسیار تودرتو را سریع می‌کند.

user:bobgroup:eng#memberfolder:plans#viewerdoc:roadmap#viewer (Check target)tuple_to_userset: follow doc#parent to folder, ask viewerowner implies editor implies viewer, then up to the Check targetuser:ana#ownertuple#editorcomputed_userset#viewercomputed_usersetmember ofviewer ofparent
text
     Check(doc:roadmap#viewer @ user:bob)       tuples: doc:roadmap#parent@folder:plans
1    rewrite doc#viewer = this + computed(editor) + ttu(parent, viewer)
2    this: no direct tuple for bob
3    computed editor -> this: none; computed owner: none
4    ttu: tuples of doc:roadmap#parent -> folder:plans -> Check(folder:plans#viewer @ bob)
5      folder viewer = this: tuple folder:plans#viewer@group:eng#member (a userset)
6      Check(group:eng#member @ bob) -> tuple group:eng#member@user:bob -> true
7    result: allowed

سناریوهای واقعی: اشتراک‌گذاری Google Drive و Docs (مثال خود مقاله)، سازمان و مخزن و تیم به سبک GitHub، درخت صفحه‌ها به سبک Notion، «اعضای پروژه تیکت‌های پروژه را ببینند» در SaaS. مقاله Calendar، Cloud، Drive، Maps، Photos و YouTube را به‌عنوان clientهای Zanzibar نام می‌برد.

عملگر rewriteمعنیمثال
thisسوژه‌هایی که مستقیم به‌صورت tuple نوشته شده‌اندdoc#viewer@user:bob
computed_usersetهمان شیء، relation دیگرowner یعنی editor یعنی viewer
tuple_to_usersetیک tuple را تا شیء دیگر دنبال کنبینندگان پوشهٔ والد
unionهر فرزند بدهدthis یا editor یا بیننده والد
intersectionهمهٔ فرزندان باید بدهندعضو و device_trusted
exclusion (but not)پایه منهای کم‌شوندهviewer but not blocked
go
// Package rebac is a small in-process relationship-based evaluator in the
// style of Google Zanzibar: relation tuples "object#relation@subject",
// usersets (a subject that is itself object#relation), and namespace
// configuration with rewrite rules (this, computed_userset, tuple_to_userset,
// union, exclusion). Tuples carry the revision at which they were added and
// removed, so a check can run at a snapshot, which is what a zookie names.
package rebac

import (
	"errors"
	"fmt"
	"sort"
	"strings"
)

// Object is "type:id".
type Object struct{ Type, ID string }

func (o Object) String() string { return o.Type + ":" + o.ID }

// Subject is a user (Relation empty) or a userset (object#relation).
type Subject struct {
	Object
	Relation string
}

func (s Subject) String() string {
	if s.Relation == "" {
		return s.Object.String()
	}
	return s.Object.String() + "#" + s.Relation
}

// User builds a plain user subject.
func User(id string) Subject { return Subject{Object: Object{"user", id}} }

// Userset builds object#relation as a subject.
func Userset(o Object, rel string) Subject { return Subject{Object: o, Relation: rel} }

// Tuple is one relation tuple: object#relation@subject.
type Tuple struct {
	Object   Object
	Relation string
	Subject  Subject
	added    int64
	removed  int64
}

func (t Tuple) String() string { return fmt.Sprintf("%s#%s@%s", t.Object, t.Relation, t.Subject) }

// Expr is a userset rewrite rule.
type Expr interface{ isExpr() }

type (
	// This means "the subjects written directly as tuples on this relation".
	This struct{}
	// Computed means "everyone who has Relation on the same object".
	Computed struct{ Relation string }
	// TupleToUserset follows the tuples of Tupleset (usually "parent") to
	// another object and asks for Relation there.
	TupleToUserset struct{ Tupleset, Relation string }
	// Union is true when any child is true.
	Union []Expr
	// Exclude is true when Base is true and Subtract is false.
	Exclude struct{ Base, Subtract Expr }
)

func (This) isExpr()           {}
func (Computed) isExpr()       {}
func (TupleToUserset) isExpr() {}
func (Union) isExpr()          {}
func (Exclude) isExpr()        {}

// Config maps type -> relation -> rewrite rule. A relation without a rule
// behaves as This.
type Config map[string]map[string]Expr

// ErrDepth is returned when the evaluation nests deeper than MaxDepth.
var ErrDepth = errors.New("rebac: evaluation too deep")

// MaxDepth bounds recursion through usersets and parents.
const MaxDepth = 25

// Store is an append-only tuple store with a revision counter.
type Store struct {
	cfg    Config
	tuples []*Tuple
	rev    int64
}

// NewStore creates a store for a configuration.
func NewStore(cfg Config) *Store { return &Store{cfg: cfg} }

// Zookie is an opaque-looking token naming a revision; clients keep it with
// the content version they protect and pass it back on later checks.
type Zookie int64

// Write adds a tuple and returns the zookie of the write.
func (s *Store) Write(o Object, rel string, sub Subject) Zookie {
	s.rev++
	s.tuples = append(s.tuples, &Tuple{Object: o, Relation: rel, Subject: sub, added: s.rev})
	return Zookie(s.rev)
}

// Delete removes a tuple (at a new revision) and returns the zookie.
func (s *Store) Delete(o Object, rel string, sub Subject) Zookie {
	s.rev++
	for _, t := range s.tuples {
		if t.removed == 0 && t.Object == o && t.Relation == rel && t.Subject == sub {
			t.removed = s.rev
		}
	}
	return Zookie(s.rev)
}

// Head is the newest zookie.
func (s *Store) Head() Zookie { return Zookie(s.rev) }

func (s *Store) live(t *Tuple, at Zookie) bool {
	return t.added <= int64(at) && (t.removed == 0 || t.removed > int64(at))
}

func (s *Store) read(o Object, rel string, at Zookie) []Subject {
	var out []Subject
	for _, t := range s.tuples {
		if t.Object == o && t.Relation == rel && s.live(t, at) {
			out = append(out, t.Subject)
		}
	}
	return out
}

// Check answers "does user have relation on object" at the newest revision.
func (s *Store) Check(o Object, rel string, user Subject) (bool, error) {
	return s.CheckAt(o, rel, user, s.Head())
}

// CheckAt answers the same question at a snapshot revision.
func (s *Store) CheckAt(o Object, rel string, user Subject, at Zookie) (bool, error) {
	return s.eval(o, rel, user, at, map[string]bool{}, 0)
}

func (s *Store) rule(o Object, rel string) Expr {
	if e, ok := s.cfg[o.Type][rel]; ok {
		return e
	}
	return This{}
}

func (s *Store) eval(o Object, rel string, user Subject, at Zookie, path map[string]bool, depth int) (bool, error) {
	if depth > MaxDepth {
		return false, ErrDepth
	}
	key := o.String() + "#" + rel
	if path[key] { // a cycle on this path contributes nothing
		return false, nil
	}
	path[key] = true
	defer delete(path, key)
	return s.expr(s.rule(o, rel), o, rel, user, at, path, depth)
}

func (s *Store) expr(e Expr, o Object, rel string, user Subject, at Zookie, path map[string]bool, depth int) (bool, error) {
	switch e := e.(type) {
	case This:
		for _, sub := range s.read(o, rel, at) {
			if sub == user {
				return true, nil
			}
			if sub.Relation != "" { // a userset such as group:eng#member
				ok, err := s.eval(sub.Object, sub.Relation, user, at, path, depth+1)
				if err != nil || ok {
					return ok, err
				}
			}
		}
		return false, nil
	case Computed:
		return s.eval(o, e.Relation, user, at, path, depth+1)
	case TupleToUserset:
		for _, sub := range s.read(o, e.Tupleset, at) {
			ok, err := s.eval(sub.Object, e.Relation, user, at, path, depth+1)
			if err != nil || ok {
				return ok, err
			}
		}
		return false, nil
	case Union:
		for _, c := range e {
			ok, err := s.expr(c, o, rel, user, at, path, depth)
			if err != nil || ok {
				return ok, err
			}
		}
		return false, nil
	case Exclude:
		base, err := s.expr(e.Base, o, rel, user, at, path, depth)
		if err != nil || !base {
			return false, err
		}
		sub, err := s.expr(e.Subtract, o, rel, user, at, path, depth)
		return !sub, err
	}
	return false, fmt.Errorf("rebac: unknown expression %T", e)
}

// ListUsers is the Expand direction: every plain user with the relation.
// It walks the rewrite rules forwards, so its cost follows the size of the
// answer and of the graph under the object.
func (s *Store) ListUsers(o Object, rel string) ([]string, error) {
	set := map[string]bool{}
	if err := s.collect(o, rel, s.Head(), set, map[string]bool{}, 0); err != nil {
		return nil, err
	}
	out := make([]string, 0, len(set))
	for u := range set {
		out = append(out, u)
	}
	sort.Strings(out)
	return out, nil
}

func (s *Store) collect(o Object, rel string, at Zookie, set, seen map[string]bool, depth int) error {
	if depth > MaxDepth {
		return ErrDepth
	}
	key := o.String() + "#" + rel
	if seen[key] {
		return nil
	}
	seen[key] = true
	return s.collectExpr(s.rule(o, rel), o, rel, at, set, seen, depth)
}

func (s *Store) collectExpr(e Expr, o Object, rel string, at Zookie, set, seen map[string]bool, depth int) error {
	switch e := e.(type) {
	case This:
		for _, sub := range s.read(o, rel, at) {
			if sub.Relation == "" {
				set[strings.TrimPrefix(sub.String(), "user:")] = true
			} else if err := s.collect(sub.Object, sub.Relation, at, set, seen, depth+1); err != nil {
				return err
			}
		}
	case Computed:
		return s.collect(o, e.Relation, at, set, seen, depth+1)
	case TupleToUserset:
		for _, sub := range s.read(o, e.Tupleset, at) {
			if err := s.collect(sub.Object, e.Relation, at, set, seen, depth+1); err != nil {
				return err
			}
		}
	case Union:
		for _, c := range e {
			if err := s.collectExpr(c, o, rel, at, set, seen, depth); err != nil {
				return err
			}
		}
	case Exclude:
		// Expand of an exclusion needs set difference; keep it honest.
		return errors.New("rebac: ListUsers does not support exclusion")
	}
	return nil
}

// ListObjects is the reverse question: which objects of a type can the user
// reach. This implementation tests every known object of the type, which is
// O(objects) checks; production systems keep a reverse index (Zanzibar's
// Leopard, SpiceDB LookupResources, OpenFGA ListObjects) instead.
func (s *Store) ListObjects(typ, rel string, user Subject) ([]string, int, error) {
	seen := map[string]bool{}
	var out []string
	checks := 0
	for _, t := range s.tuples {
		for _, o := range []Object{t.Object, t.Subject.Object} {
			if o.Type != typ || seen[o.ID] {
				continue
			}
			seen[o.ID] = true
			checks++
			ok, err := s.Check(o, rel, user)
			if err != nil {
				return nil, checks, err
			}
			if ok {
				out = append(out, o.ID)
			}
		}
	}
	sort.Strings(out)
	return out, checks, nil
}

راه‌حل / نحوهٔ استفاده: اول شیءها و relationها و parentها را مدل کنید، نه نقش‌ها را؛ configuration کوچکی مثل آنچه در تست‌ها هست (paperConfig) بنویسید و وقتی مقیاس و سازگاری و reverse index لازم شد سرویسی به سبک Zanzibar بخرید یا اجرا کنید. تست‌ها در rebac_test.go است.

سازگاری در ReBAC: zookie و مسئلهٔ new enemy حیاتی ​

به زبان ساده: اگر کسی را از پوشه حذف کنید و بعد یک سند محرمانه در آن بگذارید، حذف باید برای چکِ نگهبان آن سند دیده شود، حتی اگر یک replica کمی عقب باشد.

بدفهمی رایج: «eventual consistency برای مجوزها اشکالی ندارد.» برای دسترسی به محتوا، جواب کهنه می‌تواند نشت بدهد. مقاله این را مسئلهٔ "new enemy" می‌نامد که "can arise when we fail to respect the ordering between ACL updates or when we apply old ACLs to new content".

تعریف: Zanzibar توکن مات (opaque) می‌دهد به نام zookie که "a current global timestamp" را کد می‌کند. client آن را کنار نسخهٔ محتوایی که محافظت می‌کند ذخیره می‌کند و در چک‌های بعدی پس می‌فرستد تا چک روی snapshotی دست‌کم به تازگی آن نسخه ارزیابی شود. گوگل ACLها را در Spanner نگه می‌دارد تا TrueTime به هر نوشتن timestamp بدهد؛ دو ویژگی مقاله external consistency و snapshot read با bounded staleness است. SpiceDB توکنش را ZedToken می‌نامد و سطح‌های سازگاری دارد: minimize_latency (پیش‌فرض بیشتر APIها)، at_least_as_fresh، at_exact_snapshot، fully_consistent (پیش‌فرض نوشتن). OpenFGA روی Check و Expand و ListObjects و ListUsers مقدارهای MINIMIZE_LATENCY (پیش‌فرض) و HIGHER_CONSISTENCY را می‌دهد؛ هشدار می‌دهد که بعد از نوشتن، چک با MINIMIZE_LATENCY ممکن است از cache جواب بگیرد و تغییر را نبیند.

text
     t   Action                                              Check by Bob at doc
1    0   Alice removes Bob from folder (write, zookie Z1)
2    1   Charlie moves "salary.xlsx" into the folder; the app stores Z1 with the file
3    2   Bob opens the file; replica still at Z0 (before removal): stale check -> ALLOW (leak)
4    2'  Bob opens the file; the app passes Z1: replica waits or serves snapshot >= Z1 -> DENY

سناریوهای واقعی: جریان «اشتراک‌گذاری و بعد آپلود»؛ حذف کارمند ترک‌کننده از گروه ساعت ۱۷:۰۰ و اضافه‌کردن فایل توسط مدیر ۱۷:۰۱؛ تغییر مجوز و بلافاصله refresh صفحه (read-your-writes)؛ exportهای انبوه که باید آخرین لغوها را ببینند.

سیستمتوکنسطح‌هاپیش‌فرض
Zanzibarzookie (timestamp)snapshot در یا بعد از zookie؛ «دست‌کم به تازگی»برای سرعت روی snapshot به‌اندازهٔ کافی قدیمی ارزیابی کن
SpiceDBZedTokenminimize_latency، at_least_as_fresh، at_exact_snapshot، fully_consistentminimize_latency، جز نوشتن و schema
OpenFGAندارد (enum سازگاری)MINIMIZE_LATENCY، HIGHER_CONSISTENCYMINIMIZE_LATENCY
Ory Ketosnapshot token (طراحی Zanzibar)به مستندات نگاه کنیداینجا بررسی نشده
Permifysnapshot token (طراحی Zanzibar)به مستندات نگاه کنیداینجا بررسی نشده

راه‌حل / نحوهٔ استفاده: توکن را کنار هر نسخهٔ شیء محافظت‌شده ذخیره کنید، در هر چک همان شیء بفرستید و قوی‌ترین سطح را فقط برای معدود مسیرهایی به کار ببرید که کهنگی نشت می‌دهد (دیالوگ اشتراک، حذف). rebac.Store در Go revisionها را مدل می‌کند و تستش TestSnapshotAvoidsNewEnemy همین جدول را بازتولید می‌کند.

محصولات ReBAC: OpenFGA، SpiceDB، Ory Keto، Permify مهم ​

به زبان ساده: لازم نیست خودتان Zanzibar بسازید؛ چند سرور متن‌باز این ایده را پیاده کرده‌اند و هر کدام زبان مدل خودش را دارد.

بدفهمی رایج: «قابل‌جایگزینی‌اند.» زبان مدل، توکن‌های سازگاری، استقرار و کارایی فهرست‌کردن فرق دارد. عوض‌کردن بعدی یعنی بازنویسی مدل و وارد کردن دوبارهٔ tupleها.

تعریف: هر چهار relation tuple ذخیره می‌کنند، Check را روی schema یا مدل ارزیابی می‌کنند و APIهای فهرست‌کردن می‌دهند. OpenFGA زبان DSL دارد با define viewer: [user] or editor or viewer from parent؛ SpiceDB زبان schema با تعریف relation و permission و عملگر پیکان parent->viewer؛ Ory Keto (هستهٔ متن‌باز Ory Permissions) و Permify می‌گویند از مقالهٔ Zanzibar پیروی می‌کنند.

text
model
  schema 1.1

type user

type group
  relations
    define member: [user, group#member]

type folder
  relations
    define viewer: [user, group#member]

type document
  relations
    define parent: [folder]
    define owner: [user]
    define editor: [user, group#member] or owner
    define viewer: [user, user:*, group#member] or editor or viewer from parent
    define blocked: [user]
    define can_view: viewer but not blocked
text
definition user {}

definition group {
    relation member: user | group#member
}

definition folder {
    relation viewer: user | group#member
}

definition document {
    relation parent: folder
    relation owner: user
    relation editor: user | group#member
    relation viewer: user | group#member
    relation blocked: user

    permission edit = owner + editor
    permission view = (viewer + edit + parent->viewer) - blocked
}
text
     Operation                         OpenFGA                          SpiceDB
1    "can Ana view doc 1?"             Check(user:ana, viewer, doc:1)   CheckPermission(document:1 view user:ana)
2    "which docs can Ana view?"        ListObjects                      LookupResources
3    "who can view doc 1?"             ListUsers                        LookupSubjects
4    "what is the effective set?"      Expand                           (use LookupSubjects)
5    "add Ana as viewer"               Write tuple                      WriteRelationships

سناریوهای واقعی: SaaS چندسازمانی که کاربران عضو سازمان‌اند، سازمان‌ها مالک پروژه‌اند و پروژه‌ها مالک سند؛ هاست کد با سازمان و تیم و مخزن؛ ویرایشگر سند با ارث‌بری پوشه و لینک اشتراک (user:* برای «همه»).

محصولزبان مدلسازگاریlist objectsنکته
OpenFGADSL (define، or، and، but not، from)MINIMIZE_LATENCY پیش‌فرض، HIGHER_CONSISTENCYListObjects و نسخهٔ streamed؛ هزینه با مدل، تعداد tuple و گران‌تر بودن and و but not از or عوض می‌شودcontextual tuple اجازه می‌دهد درخواست tupleهایی بیاورد که ذخیره نشده‌اند
SpiceDB (AuthZed)definition، relation، permission، پیکان ->ZedToken و چهار سطحLookupResources، LookupSubjectsالهام‌گرفته از مقاله؛ fully_consistent برای نوشتن
Ory Ketorelation tuple و namespace (طراحی Zanzibar)به مستندات نگاه کنیدبه مستندات نگاه کنیدهستهٔ متن‌باز Ory Permissions
Permifyزبان schema (الهام‌گرفته از Zanzibar)snapshot tokenبه مستندات نگاه کنیدخود را الهام‌گرفته از Zanzibar معرفی می‌کند

راه‌حل / نحوهٔ استفاده: شناسهٔ مدل مجوز را در client ثابت (pin) کنید (SDK در Go فیلد AuthorizationModelId را در ClientConfiguration دارد)، مدل‌ها را در کنترل نسخه بنویسید، در CI بارگذاری کنید و HIGHER_CONSISTENCY یا ZedToken را فقط روی مسیرهایی بگذارید که کهنگی نشت می‌دهد. آداپتور کامپایل‌شده در Go است (بستهٔ fga).

Capability و macaroon تکمیلی ​

به زبان ساده: capability کلیدی جعل‌ناپذیر برای یک چیز است؛ هر که کلید را دارد می‌تواند استفاده کند، پس فهرستی برای جست‌وجو وجود ندارد.

بدفهمی رایج: «capability فقط یک bearer token است.» bearer token عملاً یک capability است و دقیقاً برای همین باید scope محدود و عمر کوتاه داشته باشد. پرسش پژوهشی این است که چطور دارنده بتواند پیش از دادن به دیگری آن را باریک کند.

تعریف: در امنیت مبتنی بر capability، اختیار همراه یک ارجاع جعل‌ناپذیر می‌رود (file descriptor، pre-signed URL، لینک امضاشده). macaroon (Birgisson و همکاران، NDSS 2014) اعتبارنامهٔ bearer با "contextual caveats" است: دارنده می‌تواند بدون تماس با صادرکننده با HMACهای زنجیره‌ای caveat اضافه کند (مثلاً «۵ دقیقه اعتبار»، «فقط خواندن») و verifier همهٔ caveatها را بررسی می‌کند. JWT شکل رایج‌تر توکن امضاشده است و به‌جای caveat، claim حمل می‌کند (نگاه کنید به JWT Deep Dive).

text
     Step                                          Token
1    service issues macaroon M0 for file:42        id=file:42
2    client adds caveat "action = read"            M1 = HMAC(M0.sig, "action = read")
3    client adds caveat "expires < 12:05"          M2 = HMAC(M1.sig, "expires < 12:05")
4    client hands M2 to a third party
5    verifier recomputes the chain, checks both caveats against the request -> permit or deny

سناریوهای واقعی: pre-signed URL در S3 و GCS؛ لینک اشتراک که فقط یک فایل را برای خواندن باز می‌کند؛ file descriptor که روی socket یونیکس رد می‌شود؛ سپردن یک زیرکار به سرویس دیگر با توکنی باریک‌تر.

سازوکارلغو پیش از انقضاتفویض‌پذیر و باریک‌شدنیکاربرد معمول
Pre-signed URLفقط با چرخاندن کلیدنهدسترسی موقت به فایل
JWT access tokenبا deny list یا عمر کوتاهنیاز به صدور دوبارهدسترسی API
Macaroonبا caveat روی شناسهٔ لغوبله، توسط دارندهتفویض غیرمتمرکز
tuple در ReBACبله، tuple را حذف کنیدبله، tuple بنویسیداشتراک داخل محصول

راه‌حل / نحوهٔ استفاده: برای هر اعتبارنامهٔ bearer عمر کوتاه و scope باریک بگذارید؛ وقتی لغو و فهرست‌کردن می‌خواهید از tuple در ReBAC استفاده کنید.

جداسازی چندمستاجری (Multi-tenancy) حیاتی ​

به زبان ساده: در یک محصول SaaS مشتری‌های زیادی جدول‌های یکسان را به اشتراک می‌گذارند؛ هر query باید به ردیف‌های همان مشتری فیلتر شود و فیلتر فراموش‌شده یعنی نشت داده.

بدفهمی رایج: «چک نقش از مستاجرها محافظت می‌کند.» نقش مثل admin برای هر مستاجر جداست. چک admin سراسری بدون tenant id می‌گذارد ادمین مستاجر A فاکتور مستاجر B را با id بخواند.

تعریف: شناسهٔ مستاجر (tenant_id) را در هر ردیف، هر کلید و هر درخواست مجوز حمل کنید؛ در سه جا اعمال کنید: سیاست (وقتی مستاجر کاربر با مستاجر منبع فرق دارد forbid)، لایهٔ query (global scope در Laravel، فیلتر repository) و دیتابیس (row-level security در PostgreSQL با FORCE ROW LEVEL SECURITY، چون مالک جدول در غیر این صورت معاف است). دسترسی بین مستاجرها را با 404 جواب بدهید نه 403 تا وجود id فاش نشود. مدل‌های جداسازی (schema مشترک، schema برای هر مستاجر، دیتابیس برای هر مستاجر) در Multi-Tenancy Strategies و سازوکار row-level security و roleها در Database Security است.

text
     Layer              Check                                         Stops
1    PEP                subject.tenant == resource.tenant else 404    wrong-tenant API calls
2    ORM                global scope adds WHERE tenant_id = ?         forgotten filters in new code
3    Database           RLS USING tenant_id = current_setting(...)    SQL injection, raw queries, reports
4    Cache keys         tenant id in every key                        cross-tenant cache hits
5    Object storage     prefix per tenant + scoped credentials        bucket enumeration

سناریوهای واقعی: GET /invoices/4711 با id مستاجر دیگر؛ jobای پس‌زمینه بدون زمینهٔ درخواست که SET app.tenant_id را فراموش می‌کند؛ کلید cache به شکل user:42:profile که بین مستاجرها مشترک است؛ query تحلیلی که جدول‌ها را بدون ستون مستاجر join می‌کند.

تکنیککجااز چه محافظت می‌کندشکاف
forbid سیاست روی ناهمخوانی مستاجرPDPIDOR سطح API بین مستاجرهاروی SQL خام اعمال نمی‌شود
global scope در Laravel (addGlobalScope)ORMwhere فراموش‌شده در queryهای EloquentDB::table() و queryهای خام دورش می‌زنند
RLS در PostgreSQL با set_config('app.tenant_id', ..., true)دیتابیسهر چه به جدول برسدمالک و superuser دور می‌زنند مگر FORCE؛ اگر روی session تنظیم شود در pool نشت می‌کند
schema یا دیتابیس برای هر مستاجرزیرساختشعاع انفجارهزینهٔ عملیاتی

راه‌حل / نحوهٔ استفاده: مدل Document، middleware SetTenant و schema.sql در Laravel و SQL هر سه لایه را انجام می‌دهند؛ httpguard.Enforce در Go پیش از PDP مستاجر را چک می‌کند و 404 می‌دهد.

Scope در برابر permission حیاتی ​

به زبان ساده: scope در OAuth چیزی است که کاربر به یک برنامه اجازه داده از طرفش انجام دهد؛ permission چیزی است که کاربر اصلاً حق دارد. حق مؤثر اشتراک این دو است.

بدفهمی رایج: «scope vs permission یکی است و فهرست scope توکن مجوز من است.» توکنی با scope invoices:write برای کاربری که مجوز نوشتن ندارد باید رد شود، و کاربری که مجوز دارد ولی توکنش فقط profile دارد هم باید رد شود. RFC 6749 بخش 3.3 scope را "the scope of the access request" تعریف می‌کند، فهرستی از رشته‌های جداشده با فاصله و حساس به حروف که "defined by the authorization server"؛ تفویضِ مالک منبع را حمل می‌کند نه حقوق کاربر را.

تعریف: دسترسی مؤثر = (حقوق کاربر، از RBAC/ABAC/ReBAC) AND (scopeهایی که این کاربر به این client داده). توکن‌های client-credentials کاربر ندارند: مجوزهایشان مجوز هویت سرویس است که معمولاً به‌صورت scope یا role در توکن می‌آید. جزئیات scope و رضایت و توکن در OAuth 2.0, OpenID Connect & SSO است.

text
     Token (user ana, client "calendar-app")   scope = "invoices:read"
1    GET /invoices/9           needs invoices:read  scope ok;  ana may read invoice 9?  yes  -> permit
2    PUT /invoices/9           needs invoices:write scope missing                           -> 403 insufficient_scope
3    token of "admin-app"      scope = "invoices:write"  ana has no write permission        -> 403 (permission denied)
جنبهScopePermission
چه کسی می‌دهدمالک منبع هنگام رضایتمدیر یا خود سیستم
به چه کسیبرنامهٔ client که از طرف کاربر عمل می‌کندکاربر یا هویت سرویس
کجا زندگی می‌کنددر access token (یا نتیجهٔ introspection)در سیستم مجوزدهی
چه کسی چک می‌کنداعتبارسنجی توکن در APIPDP
لغوgrant یا توکن را لغو کنیدنقش، ویژگی یا tuple را عوض کنید

راه‌حل / نحوهٔ استفاده: scope را در لبه اعتبارسنجی کنید، بعد PDP را با کاربر به‌عنوان subject صدا بزنید؛ هرگز فقط چون توکن scope دارد به کاربر مجوز ندهید.

Policy as code و تست سیاست مهم ​

به زبان ساده: سیاست‌ها در فایل نوشته می‌شوند، در pull request بازبینی می‌شوند، ماشین تستشان می‌کند و مثل نرم‌افزار deploy می‌شوند.

بدفهمی رایج: «تست‌های برنامه سیاست را پوشش می‌دهند.» تست‌های برنامه معمولاً مسیر خوشحال را می‌سنجند. تست سیاست ماتریس را می‌گوید: برای هر نقش یا مجموعه ویژگی، کدام کارها مجاز و کدام ممنوع است، از جمله مواردی که هرگز نباید مجاز شوند.

تعریف: policy as code یعنی سیاست‌ها در کنترل نسخه‌اند، تست دارند، از بررسی‌های ایستا می‌گذرند (opa check در OPA، اعتبارسنجی Cedar با schema)، از طریق PAP منتشر می‌شوند (bundleهای OPA، policy storeهای Cedar) و decision log می‌نویسند. OPA اجراگر تست داخلی دارد (opa test)؛ Cedar سیاست را با schema اعتبارسنجی می‌کند.

text
     Step                          Command                                  Gate
1    edit policies/authz.rego      git diff reviewed in a pull request
2    run policy tests              opa test policies -v                     3/3 PASS
3    run Go decider tests          go test ./...                            cedarx, abac, rbac, rebac
4    publish bundle                CI builds and signs a bundle             PAP
5    PDP loads bundle              decision logs include bundle revision    audit
نوع تستچه چیزی را ثابت می‌کندابزار
تست جدولی برای هر نقش یا مجموعه ویژگیماتریس permit و denyopa test، تست جدولی Go، PHPUnit
تست منفیچیزهایی که هرگز نباید مجاز شوند (بین مستاجرها)همان‌ها
تست ویژگی یا invariant«هیچ تصمیمی به فیلدی که client می‌فرستد وابسته نیست»fuzz test
اعتبارسنجی schemaسیاست‌ها به ویژگی‌های واقعی ارجاع می‌دهندvalidator در Cedar
shadow modeسیاست جدید کنار قدیمی ارزیابی و تفاوت‌ها لاگ می‌شودdecision log
rego
package authz_test

import rego.v1

import data.authz

base := {
	"Subject": "ana", "SubjectTenant": "acme", "Action": "read",
	"SubjectAttrs": {"department": "finance"},
	"Resource": {"Tenant": "acme", "Attrs": {"department": "finance", "owner": "bob"}},
	"Env": {"hour": "10"},
}

test_department_read_in_hours if authz.allow with input as base

test_other_tenant_denied if not authz.allow with input as object.union(base, {"Resource": {"Tenant": "globex", "Attrs": {"department": "finance"}}})

test_after_hours_denied if not authz.allow with input as object.union(base, {"Env": {"hour": "22"}})

راه‌حل / نحوهٔ استفاده: سیاست Rego بالا در QA این فصل با OPA 1.22.4 در opa test قبول شد (۳ از ۳)؛ تست‌های Go در Go موتورهای دیگر را می‌پوشانند؛ هر دو را در CI اجرا کنید.

کارایی: کش تصمیم، batch check و مسئلهٔ فهرست‌کردن حیاتی ​

به زبان ساده: مجوزدهی در هر درخواست اجرا می‌شود پس باید سریع باشد؛ بخش سخت «آیا آنا می‌تواند این را باز کند» نیست، «آنا کدام‌یک از ۱۰٬۰۰۰ سند را می‌تواند ببیند» است.

بدفهمی رایج: «لیست را در برنامه بعد از بارگذاری فیلتر کن.» همه چیز را بار می‌کند، صفحه‌بندی را می‌شکند و تعداد را نشت می‌دهد. فهرست‌کردن مسئلهٔ reverse index است: باید از کاربر به شیءها برسید نه از شیء به کاربرها.

تعریف: چک نقطه‌ای از یک شیء گراف را می‌پیماید. پرسش فهرست («list objects») باید از کاربر شروع کند و رابطه‌ها را برعکس بپیماید یا از پیش حسابشان کند. جواب Zanzibar Leopard است، indexی ویژه برای مجموعه‌های تودرتو. دیتابیس‌ها با join جدول‌های مجوز داخل query جواب می‌دهند. محصولات ListObjects (OpenFGA) و LookupResources (SpiceDB) را می‌دهند. کش‌کردن تصمیم کهنگی را با تأخیر معامله می‌کند: TTL همان پنجرهٔ لغو است.

text
     Strategy                               Cost per list of 1,000 candidate objects
1    N point checks                         1,000 checks; in the lab, 1,001 checks for 1,001 documents
2    batch check (one round trip)           1 round trip, N evaluations on the server
3    ListObjects / LookupResources          server walks reverse edges; cost grows with the answer and model
4    denormalised permission set (per user) one read; rebuilt on tuple change; may be stale
5    filter in SQL with a reverse index     one query, uses relation_tuples_by_subject
تکنیکتأخیرکهنگیپیچیدگیوقتی استفاده کنید
کش تصمیم با TTL (مثبت ۳۰ ثانیه، منفی ۵ ثانیه)میکروثانیه در hitتا TTL بعد از لغوکمشیءهای داغ، خواندن‌محور
کلید کش نسخه‌دار (نسخهٔ مستاجر با هر نوشتن بالا می‌رود)میکروثانیهنزدیک صفرمتوسطنوشتن کم
Batch checkیک رفت‌وبرگشتمثل PDPکمیک صفحه از نتایج
مجموعهٔ مجوز denormalisedیک خواندنتا بازسازیزیادفیلتر نتایج جست‌وجو
Reverse index (relation_tuples_by_subject)یک query ایندکس‌دارمثل جدولمتوسطفهرست «چه چیزی می‌بینم»
انتقال به دیتابیس (partial evaluation، row-level security)یک queryهیچزیادفهرست‌های بزرگ با قاعده‌های ساده

راه‌حل / نحوهٔ استفاده: فقط جواب‌های قطعی را با TTL کوتاه کش کنید، هرگز خطا را کش نکنید، TTL مثبت و منفی را جدا کنید، کلید را با مستاجر، کاربر، عمل و منبع بسازید و با هر نوشتن یک نسخه را بالا ببرید (httpguard.Cache در Go و RelationshipChecker در Laravel). برای فهرست‌ها reverse index یا ListObjects به کار ببرید، نه N چک.

Audit log و explainability مهم ​

به زبان ساده: وقتی کسی می‌پرسد «چرا باب آن فایل را خواند؟» یا «چرا آنا رد شد؟» باید از روی یک سابقه جواب بدهید نه حدس.

بدفهمی رایج: «access log همان audit log است.» access log می‌گوید درخواستی رخ داد. رکورد ممیزی مجوزدهی می‌گوید چه تصمیمی، با کدام سیاست، از کدام ویژگی‌ها و در کدام نسخهٔ سیاست گرفته شد.

تعریف: رکورد audit log شامل چه کسی (subject)، چه کاری (عمل و منبع)، چه زمانی، تصمیم، دلیل یا شناسهٔ سیاست‌ها، نسخهٔ ویژگی‌ها و سیاست و شناسهٔ درخواست است. OPA decision log با decision_id می‌نویسد (REST API وقتی decision logging روشن است برمی‌گرداند)؛ Cedar diagnostics با شناسهٔ سیاست‌های تعیین‌کننده می‌دهد؛ برای OpenFGA می‌توان Check را با Expand تکمیل کرد تا «چرا» دیده شود؛ Gate::inspect() در Laravel یک Response با پیام و وضعیت برمی‌گرداند.

text
     Field            Example
1    time             2026-11-26T09:14:02Z
2    subject          user:ana (tenant acme)
3    action/resource  read doc:roadmap
4    decision         deny
5    reason/policies  forbid-unmanaged-device
6    versions         policy bundle r412, tuple zookie Z88
7    request id       7f3a... (links to the trace)
نیازسازوکارمحصول
چرا مجاز یا رد شددلیل تصمیم، شناسهٔ سیاستdiagnostics در Cedar، Response::message() در Laravel، authz.Decision.Reason و Policies
چه کسی به این شیء دسترسی داردExpand یا ListUsersOpenFGA، LookupSubjects در SpiceDB، Expand در Zanzibar
این کاربر به چه چیزی دسترسی داردListObjects یا LookupResourcesOpenFGA، SpiceDB
تاریخچهٔ ضدتخریبstore فقط‌افزودنی، ارسال به بیرون از میزبانSIEM، ذخیرهٔ WORM
بازبینی دسترسیexport دوره‌ای grantهاجدول‌های نقش و tuple

راه‌حل / نحوهٔ استفاده: هر deny و هر تغییر grant را لاگ کنید؛ تغییر grant (نقش اعطا شد، tuple نوشته شد) را رویداد امنیتی بشمارید؛ هرگز secret یا مقدار کامل توکن را لاگ نکنید. AuditFunc در Go و خط لاگ authz.decision در Laravel حداقل را در Go و Laravel نشان می‌دهند.

Zero Trust و NIST SP 800-207 حیاتی ​

به زبان ساده: بودن در شبکهٔ دفتر یا VPC تولید هیچ چیز را ثابت نمی‌کند؛ هر درخواست خودش را ثابت می‌کند و وقتی اعتماد تمام شود دسترسی هم تمام می‌شود.

بدفهمی رایج: «Zero Trust یعنی به هیچ‌کس اعتماد نکن، پس همه‌جا VPN می‌خواهیم.» Zero Trust کنترل را از لبهٔ شبکه به خود منبع می‌برد: هر درخواست احراز هویت و مجوزدهی می‌شود، با least privilege. VPN ابزار پیرامونی است و به مدل قدیمی می‌خورد.

تعریف: NIST SP 800-207 هفت اصل (tenet) فهرست می‌کند (خلاصه): (۱) همهٔ منابع داده و سرویس‌های محاسباتی «منبع» حساب می‌شوند؛ (۲) همهٔ ارتباط‌ها صرف‌نظر از موقعیت شبکه امن می‌شوند و "network location alone does not imply trust"؛ (۳) دسترسی به منبع‌ها per-session با least privilege داده می‌شود؛ (۴) دسترسی با سیاست پویا تعیین می‌شود، شامل وضعیت قابل‌مشاهدهٔ هویت client، برنامه و دستگاه درخواست‌کننده، و می‌تواند ویژگی‌های رفتاری و محیطی هم داشته باشد؛ (۵) سازمان یکپارچگی و وضعیت امنیتی همهٔ دارایی‌های خودی و وابسته را می‌سنجد، "no asset is inherently trusted"؛ (۶) همهٔ احراز هویت و مجوزدهی منابع پویا است و پیش از اجازهٔ دسترسی سخت اعمال می‌شود، "constant cycle of obtaining access, scanning and assessing threats, adapting, and continually reevaluating trust"؛ (۷) سازمان تا می‌تواند دربارهٔ وضعیت دارایی‌ها و زیرساخت و ارتباط‌ها اطلاعات جمع می‌کند و برای بهتر کردن وضعیتش به کار می‌برد. اجزای منطقی policy engine، policy administrator و policy enforcement point هستند.

Subjectuser or serviceany networkPEPgateway or proxyper-session grantResourceAPI, app, dataPDP = Policy Engine + Policy Administratordecides, then tells the PEP to open or close the sessionIdentityuser, MFA, workload idDevice posturepatched, managed, attestedThreat intelfeeds, alertsActivity logsbehaviour, SIEMtrust is per session,around the resource,re-evaluated continuously
text
     t       Event                                              Decision
1    09:00   Ana signs in with MFA from a managed laptop        session granted: finance-app, read
2    09:40   device agent reports an outdated OS patch          PE re-evaluates: write actions removed
3    10:15   same session requests the payroll app              new resource, new decision: deny (not in her policy)
4    11:00   threat feed flags her IP range                     PA tells the PEP to terminate the session
5    11:05   re-authentication with a hardware key              new session, low-risk attributes restored

سناریوهای واقعی: proxy آگاه از هویت جلوی برنامه‌های داخلی؛ mTLS بین سرویس‌ها با هویت به سبک SPIFFE؛ مجوزدهی per-request در میکروسرویس‌ها به‌جای «شبکهٔ داخلی، مورد اعتماد»؛ conditional access که ورود از دستگاه ناسازگار را رد می‌کند.

تم اصل NISTچه پیاده می‌کنیدنمونه محصول
به شبکه اعتماد نکنPEP جلوی هر منبع؛ mTLS بین سرویس‌هاEnvoy، Istio، Linkerd، proxyهای آگاه از هویت
صریح تأیید کناحراز هویت قوی به‌علاوهٔ دستگاه و زمینهارائه‌دهندگان OIDC، WebAuthn، MDM
Least privilegeمجوز باریک، اعطای just-in-time و زمان‌دارAWS IAM Identity Center، نقش‌های spatie با انقضا
Continuous verificationارزیابی دوبارهٔ نشست، توکن کوتاه‌عمرعمر توکن در حد دقیقه، رویدادهای به سبک CAEP
فرض را بر نفوذ بگذارتقسیم‌بندی، لاگ، تشخیص ناهنجاریSIEM، network policy

راه‌حل / نحوهٔ استفاده: از منبع‌ها شروع کنید نه شبکه: فهرستشان کنید، جلوی هرکدام PEP بگذارید، ویژگی‌ها (کاربر، دستگاه، ریسک) را تعریف کنید و اولین سیاست را «deny مگر قاعده‌ای صریح اجازه دهد» بگذارید.

Zero Trust در عمل: BeyondCorp، ZTNA، device posture، mTLS مهم ​

به زبان ساده: گوگل شبکهٔ داخلی‌اش را مورد اعتماد نشمرد و دسترسی را به کاربر و دستگاه وابسته کرد، و صنعت آن را به محصول تبدیل کرد.

بدفهمی رایج: «ZTNA جای VPN را می‌گیرد و همین Zero Trust است.» ZTNA (Zero Trust Network Access) اصطلاح صنعتی برای دسترسی به برنامه‌ها از طریق gateway بدون دسترسی سطح شبکه است؛ بخشی از معماری را می‌پوشاند. خود NIST SP 800-207 رویکردهایی مثل حاکمیت هویت پیشرفته، micro-segmentation و زیرساخت شبکه با software defined perimeter را شرح می‌دهد؛ مخفف ZTNA را به کار نمی‌برد (در نسخهٔ ذخیره‌شدهٔ PDF موردی پیدا نشد).

تعریف: BeyondCorp (Ward و Beyer، ۲۰۱۴) کنترل دسترسی را "from the perimeter" به دستگاه و کاربر منتقل کرد؛ ادامهٔ ۲۰۱۶، "Design to Deployment at Google"، "an access model with dynamic tiers of trust for devices" را شرح می‌دهد. Device posture مجموعهٔ سیگنال دربارهٔ client است: مدیریت‌شده یا نه، نسخهٔ OS و وصله‌ها، رمزگذاری دیسک، قفل صفحه، attestation. Continuous verification این‌ها را حین نشست دوباره بررسی می‌کند. بین سرویس‌ها هویت گواهی workload است (نگاه کنید به Mutual TLS & Securing Service-to-Service Traffic و Service Mesh & the Sidecar Pattern) و سیاست‌های مجوز در mesh (AuthorizationPolicy در Istio، فیلتر RBAC در Envoy) هم PEP‌اند هم PDP.

لایههویتمجوزدهینمونه
کاربر به برنامهورود OIDC، MFA، گواهی دستگاهسیاست برنامه به‌علاوهٔ سطح دستگاهproxy آگاه از هویت
برنامه به برنامهگواهی workload (mTLS)سیاست mesh بر پایهٔ هویت سرویسIstio، Linkerd
برنامه به دادهrole دیتابیس یا اعتبارنامهٔ کوتاه‌عمرrow-level security، grant سطح ستونroleها و RLS در PostgreSQL
دسترسی مدیرارتقای just-in-timeاعطای نقش زمان‌دارنقش break-glass با expires_at

راه‌حل / نحوهٔ استفاده: ویژگی‌های دستگاه را به درخواست PEP اضافه کنید (Env["device_managed"])، سیاست را روی posture بد forbid کنید (قاعدهٔ forbid-unmanaged-device در ABAC را ببینید) و نشست و توکن را کوتاه نگه دارید.

سازوکار ​

knobها و جایشان ​

محصولKnobمعنیپیش‌فرض یا نکته
Laravel GateGate::before / Gate::afterپیش یا پس از هر چک ability اجرا می‌شود؛ نتیجهٔ غیر null نهایی استnull بدهید تا ادامه یابد
Laravel Policybefore(User, string $ability)میان‌بُر هر policynull بدهید تا ادامه یابد
LaravelGate::guessPolicyNamesUsingکشف سفارشی policyپیش‌فرض: پوشهٔ Policies کنار مدل‌ها، پسوند Policy
Laravelattribute ‏#[UsePolicy(...)]مدل را به policyاش وصل می‌کندجایگزین Gate::policy
route در Laravelalias ‏can:update,postپیش از controller مجوز می‌دهدalias را Laravel ثبت می‌کند
spatie/laravel-permissionassignRole، givePermissionTo، hasPermissionToنقش و مجوز روی کاربرhasPermissionTo از Gate رد نمی‌شود پس Gate::before اعمال نمی‌شود
OPAdefault allow := falseوقتی هیچ قاعده‌ای نخورد تعریف‌شده باشدبدون آن نتیجه undefined است
OPA RESTPOST /v1/data/<path> با {"input": ...}یک قاعده را ارزیابی کن200 بدون result وقتی undefined است؛ 400 برای ورودی بد
Cedarpermit، forbid، when، unlessاثر و شرط‌هاdeny مگر permitی بخورد و forbidی نخورد
OpenFGAسازگاری MINIMIZE_LATENCY یا HIGHER_CONSISTENCYcache در برابر تازگیMINIMIZE_LATENCY
OpenFGA SDKAuthorizationModelIdثابت‌کردن نسخهٔ مدلتنظیم‌نشده یعنی آخرین
SpiceDBconsistency روی درخواستminimize_latency، at_least_as_fresh، at_exact_snapshot، fully_consistentپیش‌فرض minimize_latency برای بیشتر APIها
PostgreSQLFORCE ROW LEVEL SECURITYسیاست‌ها را روی مالک جدول هم اعمال کنوگرنه مالک معاف است
PostgreSQLset_config('app.tenant_id', v, true)تنظیم محلی تراکنشtrue یعنی محلی؛ با pool امن است

جریان درخواست و جایی که هر شکست می‌افتد ​

text
     Stage                      Failure                           Status   Fail mode
1    authenticate               missing or invalid credentials    401      deny
2    scope check                token lacks required scope        403      deny (insufficient_scope)
3    tenant check               subject tenant differs            404      deny
4    PDP call                   timeout, 5xx, undefined result    503      deny (fail closed)
5    decision                   deny                              403      deny
6    handler                    permit                            2xx      -
7    audit                      write failure                     -        alert; do not block reads, do block grant changes

نام خطاهایی که می‌بینید ​

کجانام یا پیاممعنی
LaravelIlluminate\Auth\Access\AuthorizationException (HTTP 403)Gate::authorize رد کرد
LaravelResponse::denyAsNotFound()رد با وضعیت 404
LaravelResponse::denyWithStatus(404)رد با وضعیت دلخواه
spatieSpatie\Permission\Exceptions\UnauthorizedExceptionتوسط middleware خود بسته بالا می‌آید
OPAHTTP 200 با {}قاعده undefined: آن را deny بشمارید
OPAHTTP 400سند ورودی نامعتبر
Go rbacErrSSD، ErrDSD، ErrCycleنقض قید یا سلسله‌مراتب
Go rebacErrDepthارزیابی عمیق‌تر از MaxDepth (25)
Go httpguardErrUndefinedOPA بدون result جواب داد
OAuthinsufficient_scopeتوکن scope لازم را ندارد؛ خطای bearer-token
PostgreSQLnew row violates row-level security policy for table "invoices" (SQLSTATE 42501)WITH CHECK نوشتن را رد کرد

Go ​

ماژول Go (پوشهٔ go/، ماژول academy/authorization-rbac-abac-zero-trust) برای هر مدل یک بسته دارد و همه پشت یک رابط authz.Decider هستند؛ پس handler مهم نیست جواب از نقش می‌آید یا ویژگی یا رابطه. وابستگی‌ها فقط cedar-go و go-sdk رسمی OpenFGA است (هر دو در go.mod خود Go 1.26 می‌خواهند، پس این ماژول go 1.26.0 دارد).

نمونه: واژگان مشترک ​

go
// Package authz holds the vocabulary shared by every model in this chapter:
// a request (who, what action, which resource, in which context) and a
// decision (allow or deny, with the reason and the policies that decided it).
package authz

import "context"

// Resource is the thing being accessed. Tenant is the owner tenant and must
// be checked before any model is consulted.
type Resource struct {
	Type   string
	ID     string
	Tenant string
	Attrs  map[string]string
}

// Request is what a policy enforcement point (PEP) sends to a policy
// decision point (PDP).
type Request struct {
	Subject       string
	SubjectTenant string
	SubjectAttrs  map[string]string
	Action        string
	Resource      Resource
	Env           map[string]string
}

// Decision is the PDP answer. Reason and Policies make it explainable.
type Decision struct {
	Allow    bool
	Reason   string
	Policies []string
}

// Decider is a policy decision point (PDP).
type Decider interface {
	Decide(ctx context.Context, r Request) (Decision, error)
}

// DeciderFunc adapts a function to Decider.
type DeciderFunc func(ctx context.Context, r Request) (Decision, error)

// Decide implements Decider.
func (f DeciderFunc) Decide(ctx context.Context, r Request) (Decision, error) { return f(ctx, r) }

// Deny builds a deny decision with a reason.
func Deny(reason string) Decision { return Decision{Allow: false, Reason: reason} }

نمونه: RBAC با سلسله‌مراتب و separation of duties ​

go
// Package rbac is an in-process implementation of the NIST RBAC reference
// model: users, roles, permissions, a role hierarchy (a senior role inherits
// the permissions of its junior roles), static separation of duty (SSD) at
// assignment time, and dynamic separation of duty (DSD) at session time.
package rbac

import (
	"context"
	"errors"
	"fmt"
	"sort"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

type (
	Role       string
	Permission string
)

// ErrSSD is returned when an assignment would break a static SoD constraint.
var ErrSSD = errors.New("rbac: static separation of duty violated")

// ErrDSD is returned when activating roles would break a dynamic constraint.
var ErrDSD = errors.New("rbac: dynamic separation of duty violated")

// ErrCycle is returned when a hierarchy edge would create a cycle.
var ErrCycle = errors.New("rbac: role hierarchy cycle")

// Constraint says: no user (SSD) or session (DSD) may hold N or more roles
// of Roles at the same time.
type Constraint struct {
	Roles []Role
	N     int
}

// Model holds the whole RBAC state.
type Model struct {
	perms   map[Role]map[Permission]bool
	juniors map[Role][]Role
	assign  map[string]map[Role]bool
	ssd     []Constraint
	dsd     []Constraint
}

// New returns an empty model.
func New() *Model {
	return &Model{
		perms:   map[Role]map[Permission]bool{},
		juniors: map[Role][]Role{},
		assign:  map[string]map[Role]bool{},
	}
}

// Grant gives a permission to a role.
func (m *Model) Grant(r Role, p Permission) {
	if m.perms[r] == nil {
		m.perms[r] = map[Permission]bool{}
	}
	m.perms[r][p] = true
}

// Inherit makes senior inherit everything junior can do.
func (m *Model) Inherit(senior, junior Role) error {
	if senior == junior || m.reaches(junior, senior) {
		return fmt.Errorf("%w: %s -> %s", ErrCycle, senior, junior)
	}
	m.juniors[senior] = append(m.juniors[senior], junior)
	return nil
}

func (m *Model) reaches(from, to Role) bool {
	for _, j := range m.juniors[from] {
		if j == to || m.reaches(j, to) {
			return true
		}
	}
	return false
}

// AddSSD registers a static separation-of-duty constraint.
func (m *Model) AddSSD(c Constraint) { m.ssd = append(m.ssd, c) }

// AddDSD registers a dynamic separation-of-duty constraint.
func (m *Model) AddDSD(c Constraint) { m.dsd = append(m.dsd, c) }

// closure returns the roles plus every junior reachable through the hierarchy.
func (m *Model) closure(roles map[Role]bool) map[Role]bool {
	out := map[Role]bool{}
	var walk func(Role)
	walk = func(r Role) {
		if out[r] {
			return
		}
		out[r] = true
		for _, j := range m.juniors[r] {
			walk(j)
		}
	}
	for r := range roles {
		walk(r)
	}
	return out
}

func violates(cs []Constraint, held map[Role]bool) bool {
	for _, c := range cs {
		n := 0
		for _, r := range c.Roles {
			if held[r] {
				n++
			}
		}
		if n >= c.N {
			return true
		}
	}
	return false
}

// Assign gives a user a role unless it breaks an SSD constraint. The check
// uses the hierarchy closure, because a senior role implies its juniors.
func (m *Model) Assign(user string, r Role) error {
	next := map[Role]bool{r: true}
	for k := range m.assign[user] {
		next[k] = true
	}
	if violates(m.ssd, m.closure(next)) {
		return fmt.Errorf("%w: %s cannot also be %s", ErrSSD, user, r)
	}
	if m.assign[user] == nil {
		m.assign[user] = map[Role]bool{}
	}
	m.assign[user][r] = true
	return nil
}

// Revoke removes a role from a user.
func (m *Model) Revoke(user string, r Role) { delete(m.assign[user], r) }

// Permissions is the effective permission set of a user (all assigned roles).
func (m *Model) Permissions(user string) []Permission {
	return m.permsOf(m.assign[user])
}

func (m *Model) permsOf(roles map[Role]bool) []Permission {
	set := map[Permission]bool{}
	for r := range m.closure(roles) {
		for p := range m.perms[r] {
			set[p] = true
		}
	}
	out := make([]Permission, 0, len(set))
	for p := range set {
		out = append(out, p)
	}
	sort.Slice(out, func(i, j int) bool { return out[i] < out[j] })
	return out
}

// Can reports whether the user holds the permission through any role.
func (m *Model) Can(user string, p Permission) bool {
	for _, q := range m.Permissions(user) {
		if q == p {
			return true
		}
	}
	return false
}

// Session is a subset of the user's roles activated for one login.
type Session struct {
	m      *Model
	user   string
	active map[Role]bool
}

// StartSession activates roles for a user; they must be assigned and must
// satisfy every DSD constraint.
func (m *Model) StartSession(user string, roles ...Role) (*Session, error) {
	act := map[Role]bool{}
	for _, r := range roles {
		if !m.assign[user][r] {
			return nil, fmt.Errorf("rbac: %s is not assigned %s", user, r)
		}
		act[r] = true
	}
	if violates(m.dsd, m.closure(act)) {
		return nil, fmt.Errorf("%w: %s", ErrDSD, user)
	}
	return &Session{m: m, user: user, active: act}, nil
}

// Can checks only the permissions of the activated roles.
func (s *Session) Can(p Permission) bool {
	for _, q := range s.m.permsOf(s.active) {
		if q == p {
			return true
		}
	}
	return false
}

// Authorizer adapts the model to authz.Decider. The permission string is
// "<resource type>:<action>".
type Authorizer struct{ M *Model }

// Decide implements authz.Decider.
func (a Authorizer) Decide(_ context.Context, r authz.Request) (authz.Decision, error) {
	p := Permission(r.Resource.Type + ":" + r.Action)
	if a.M.Can(r.Subject, p) {
		return authz.Decision{Allow: true, Reason: "role grants " + string(p)}, nil
	}
	return authz.Deny("no role of " + r.Subject + " grants " + string(p)), nil
}
go
package rbac

import (
	"errors"
	"testing"
)

func build(t *testing.T) *Model {
	t.Helper()
	m := New()
	m.Grant("viewer", "invoice:read")
	m.Grant("clerk", "invoice:create")
	m.Grant("approver", "invoice:approve")
	if err := m.Inherit("clerk", "viewer"); err != nil {
		t.Fatal(err)
	}
	// One person may not both create and approve an invoice.
	m.AddSSD(Constraint{Roles: []Role{"clerk", "approver"}, N: 2})
	return m
}

func TestHierarchyInheritsJuniorPermissions(t *testing.T) {
	m := build(t)
	if err := m.Assign("ana", "clerk"); err != nil {
		t.Fatal(err)
	}
	for _, p := range []Permission{"invoice:read", "invoice:create"} {
		if !m.Can("ana", p) {
			t.Errorf("ana should have %s", p)
		}
	}
	if m.Can("ana", "invoice:approve") {
		t.Error("ana must not approve")
	}
}

func TestStaticSeparationOfDuty(t *testing.T) {
	m := build(t)
	_ = m.Assign("bob", "clerk")
	if err := m.Assign("bob", "approver"); !errors.Is(err, ErrSSD) {
		t.Fatalf("want ErrSSD, got %v", err)
	}
}

func TestCycleRejected(t *testing.T) {
	m := build(t)
	if err := m.Inherit("viewer", "clerk"); !errors.Is(err, ErrCycle) {
		t.Fatalf("want ErrCycle, got %v", err)
	}
}

func TestDynamicSeparationOfDuty(t *testing.T) {
	m := New()
	m.Grant("teller", "till:open")
	m.Grant("auditor", "till:audit")
	m.AddDSD(Constraint{Roles: []Role{"teller", "auditor"}, N: 2})
	_ = m.Assign("eve", "teller")
	_ = m.Assign("eve", "auditor") // allowed: DSD only limits one session
	if _, err := m.StartSession("eve", "teller", "auditor"); !errors.Is(err, ErrDSD) {
		t.Fatalf("want ErrDSD, got %v", err)
	}
	s, err := m.StartSession("eve", "auditor")
	if err != nil {
		t.Fatal(err)
	}
	if s.Can("till:open") || !s.Can("till:audit") {
		t.Error("session must only carry the active role")
	}
}

نمونه: قاعده‌های ABAC با deny-overrides ​

go
// Package abac evaluates attribute policies over the four attribute groups of
// NIST SP 800-162: subject, resource, action and environment. Combining is
// deny-overrides with default deny, the same shape as Cedar's forbid-wins.
package abac

import (
	"context"
	"strconv"
	"time"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

// Effect of a rule that matches.
type Effect int

const (
	Permit Effect = iota
	Forbid
)

// Rule is one policy: an ID for the audit log, an effect and a condition.
type Rule struct {
	ID     string
	Effect Effect
	When   func(r authz.Request) bool
}

// Engine is a policy decision point (PDP) over a rule list.
type Engine struct{ Rules []Rule }

// Decide implements authz.Decider.
func (e Engine) Decide(_ context.Context, r authz.Request) (authz.Decision, error) {
	var permits []string
	for _, rule := range e.Rules {
		if !rule.When(r) {
			continue
		}
		if rule.Effect == Forbid {
			return authz.Decision{Reason: "forbidden by " + rule.ID, Policies: []string{rule.ID}}, nil
		}
		permits = append(permits, rule.ID)
	}
	if len(permits) == 0 {
		return authz.Deny("no policy permits the request (default deny)"), nil
	}
	return authz.Decision{Allow: true, Reason: "permitted by " + permits[0], Policies: permits}, nil
}

// Example rules for a document service, used by the tests and the lab.

// DocumentRules returns the example policies: two forbid rules that always win
// and two permit rules.
func DocumentRules() []Rule {
	return []Rule{
		{ID: "forbid-cross-tenant", Effect: Forbid, When: func(r authz.Request) bool {
			return r.SubjectTenant != r.Resource.Tenant
		}},
		{ID: "forbid-unmanaged-device", Effect: Forbid, When: func(r authz.Request) bool {
			return r.Resource.Attrs["classification"] == "confidential" && r.Env["device_managed"] != "true"
		}},
		{ID: "permit-owner-edit", Effect: Permit, When: func(r authz.Request) bool {
			return r.Action == "edit" && r.Resource.Attrs["owner"] == r.Subject
		}},
		{ID: "permit-dept-read-business-hours", Effect: Permit, When: func(r authz.Request) bool {
			if r.Action != "read" || r.SubjectAttrs["department"] != r.Resource.Attrs["department"] {
				return false
			}
			h, err := strconv.Atoi(r.Env["hour"])
			return err == nil && h >= 8 && h < 18
		}},
	}
}

// Hour formats a time for the Env map.
func Hour(t time.Time) string { return strconv.Itoa(t.Hour()) }
go
package abac

import (
	"context"
	"testing"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

func req(mod func(*authz.Request)) authz.Request {
	r := authz.Request{
		Subject: "ana", SubjectTenant: "acme",
		SubjectAttrs: map[string]string{"department": "finance"},
		Action:       "read",
		Resource: authz.Resource{Type: "doc", ID: "1", Tenant: "acme",
			Attrs: map[string]string{"owner": "bob", "department": "finance", "classification": "internal"}},
		Env: map[string]string{"hour": "10", "device_managed": "true"},
	}
	mod(&r)
	return r
}

func TestDecisions(t *testing.T) {
	e := Engine{Rules: DocumentRules()}
	cases := []struct {
		name string
		mod  func(*authz.Request)
		want bool
	}{
		{"dept read in hours", func(*authz.Request) {}, true},
		{"after hours", func(r *authz.Request) { r.Env["hour"] = "22" }, false},
		{"other tenant forbid wins", func(r *authz.Request) { r.Resource.Tenant = "globex" }, false},
		{"confidential on unmanaged device", func(r *authz.Request) {
			r.Resource.Attrs["classification"] = "confidential"
			r.Env["device_managed"] = "false"
		}, false},
		{"owner edit", func(r *authz.Request) { r.Action = "edit"; r.Resource.Attrs["owner"] = "ana" }, true},
		{"no matching permit", func(r *authz.Request) { r.Action = "delete" }, false},
	}
	for _, c := range cases {
		d, err := e.Decide(context.Background(), req(c.mod))
		if err != nil || d.Allow != c.want {
			t.Errorf("%s: allow=%v want %v (%s)", c.name, d.Allow, c.want, d.Reason)
		}
	}
}

نمونه: ReBAC (مدل Zanzibar درون‌فرایندی) ​

ارزیاب همان کدی است که در بلوک ReBAC آمد. تست‌هایش پیکربندی شکل ۱ مقالهٔ Zanzibar، userset، parent، چرخه، exclusion و مسئلهٔ new enemy را بازتولید می‌کنند.

go
package rebac

import (
	"reflect"
	"testing"
)

// The namespace configuration of Figure 1 in the Zanzibar paper: owners are
// editors, editors are viewers, and viewers of the parent folder are viewers.
func paperConfig() Config {
	return Config{
		"doc": {
			"owner":  This{},
			"editor": Union{This{}, Computed{"owner"}},
			"viewer": Union{This{}, Computed{"editor"}, TupleToUserset{"parent", "viewer"}},
		},
		"folder": {
			"viewer": This{},
		},
		"group": {"member": This{}},
	}
}

func fixture() (*Store, Object, Object) {
	s := NewStore(paperConfig())
	folder := Object{"folder", "plans"}
	doc := Object{"doc", "roadmap"}
	s.Write(doc, "parent", Subject{Object: folder})
	s.Write(doc, "owner", User("ana"))
	s.Write(folder, "viewer", Userset(Object{"group", "eng"}, "member"))
	s.Write(Object{"group", "eng"}, "member", User("bob"))
	return s, folder, doc
}

func TestRewriteRules(t *testing.T) {
	s, _, doc := fixture()
	cases := []struct {
		user, rel string
		want      bool
	}{
		{"ana", "owner", true},
		{"ana", "editor", true}, // computed_userset: owner implies editor
		{"ana", "viewer", true},
		{"bob", "viewer", true},  // group usersets plus tuple_to_userset via parent
		{"bob", "editor", false}, // viewing does not imply editing
		{"eve", "viewer", false},
	}
	for _, c := range cases {
		got, err := s.Check(doc, c.rel, User(c.user))
		if err != nil || got != c.want {
			t.Errorf("%s %s: got %v err %v want %v", c.user, c.rel, got, err, c.want)
		}
	}
}

func TestListUsersAndObjects(t *testing.T) {
	s, _, doc := fixture()
	users, err := s.ListUsers(doc, "viewer")
	if err != nil || !reflect.DeepEqual(users, []string{"ana", "bob"}) {
		t.Fatalf("users %v err %v", users, err)
	}
	objs, checks, err := s.ListObjects("doc", "viewer", User("bob"))
	if err != nil || !reflect.DeepEqual(objs, []string{"roadmap"}) || checks != 1 {
		t.Fatalf("objs %v checks %d err %v", objs, checks, err)
	}
}

func TestSnapshotAvoidsNewEnemy(t *testing.T) {
	s, _, doc := fixture()
	before := s.Head()
	z := s.Delete(Object{"group", "eng"}, "member", User("bob")) // bob removed
	stale, _ := s.CheckAt(doc, "viewer", User("bob"), before)
	fresh, _ := s.CheckAt(doc, "viewer", User("bob"), z)
	if !stale || fresh {
		t.Fatalf("stale=%v fresh=%v; a check at the zookie must see the removal", stale, fresh)
	}
}

func TestCycleAndDepth(t *testing.T) {
	s := NewStore(Config{"group": {"member": This{}}})
	a, b := Object{"group", "a"}, Object{"group", "b"}
	s.Write(a, "member", Userset(b, "member"))
	s.Write(b, "member", Userset(a, "member"))
	ok, err := s.Check(a, "member", User("zed"))
	if err != nil || ok {
		t.Fatalf("cycle must terminate with false, got %v %v", ok, err)
	}
}

func TestExclusion(t *testing.T) {
	cfg := Config{"doc": {
		"viewer":   This{},
		"blocked":  This{},
		"can_view": Exclude{Base: Computed{"viewer"}, Subtract: Computed{"blocked"}},
	}}
	s := NewStore(cfg)
	d := Object{"doc", "x"}
	s.Write(d, "viewer", User("kim"))
	s.Write(d, "blocked", User("kim"))
	if ok, _ := s.Check(d, "can_view", User("kim")); ok {
		t.Fatal("blocked user must not view")
	}
}

نمونه: نقطهٔ اعمال، کش تصمیم و client برای OPA ​

go
// Package httpguard is the policy enforcement point (PEP) for net/http: it
// builds a request for the decision point, fails closed on any error, checks
// the tenant before the model, writes an audit record, and can cache
// decisions for a short time.
package httpguard

import (
	"bytes"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net/http"
	"sync"
	"time"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

// Extractor turns an HTTP request into an authorization request. Returning
// an error means "unauthenticated" and produces 401.
type Extractor func(*http.Request) (authz.Request, error)

// AuditFunc receives every decision, including errors.
type AuditFunc func(authz.Request, authz.Decision, error)

// Enforce wraps next. Order: authenticate, tenant check, decision, audit.
func Enforce(d authz.Decider, ex Extractor, audit AuditFunc, next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, hr *http.Request) {
		req, err := ex(hr)
		if err != nil {
			http.Error(w, "unauthenticated", http.StatusUnauthorized)
			return
		}
		var dec authz.Decision
		switch {
		case req.SubjectTenant != req.Resource.Tenant:
			// Cross-tenant access is answered as "not found" so ids do not leak.
			dec = authz.Deny("tenant mismatch")
		default:
			dec, err = d.Decide(hr.Context(), req)
		}
		if audit != nil {
			audit(req, dec, err)
		}
		switch {
		case err != nil: // PDP unreachable or broken: fail closed
			http.Error(w, "authorization unavailable", http.StatusServiceUnavailable)
		case req.SubjectTenant != req.Resource.Tenant:
			http.NotFound(w, hr)
		case !dec.Allow:
			http.Error(w, "forbidden", http.StatusForbidden)
		default:
			next.ServeHTTP(w, hr)
		}
	})
}

// Cache wraps a Decider with a small TTL cache. Positive and negative
// decisions get separate lifetimes: a long positive TTL is the window in
// which a revoked permission still works.
type Cache struct {
	Inner       authz.Decider
	PositiveTTL time.Duration
	NegativeTTL time.Duration
	Now         func() time.Time

	mu      sync.Mutex
	entries map[string]entry
	Hits    int
	Misses  int
}

type entry struct {
	d   authz.Decision
	exp time.Time
}

func key(r authz.Request) string {
	return fmt.Sprintf("%s|%s|%s|%s:%s|%s", r.SubjectTenant, r.Subject, r.Action, r.Resource.Type, r.Resource.ID, r.Resource.Tenant)
}

// Decide implements authz.Decider. Errors are never cached.
func (c *Cache) Decide(ctx context.Context, r authz.Request) (authz.Decision, error) {
	now := c.Now()
	k := key(r)
	c.mu.Lock()
	if e, ok := c.entries[k]; ok && now.Before(e.exp) {
		c.Hits++
		c.mu.Unlock()
		return e.d, nil
	}
	c.Misses++
	c.mu.Unlock()
	d, err := c.Inner.Decide(ctx, r)
	if err != nil {
		return d, err
	}
	ttl := c.NegativeTTL
	if d.Allow {
		ttl = c.PositiveTTL
	}
	c.mu.Lock()
	if c.entries == nil {
		c.entries = map[string]entry{}
	}
	c.entries[k] = entry{d, now.Add(ttl)}
	c.mu.Unlock()
	return d, nil
}

// OPA calls an Open Policy Agent server over its REST Data API:
// POST /v1/data/<path> with {"input": ...} and reads {"result": ...}.
type OPA struct {
	BaseURL string // for example http://127.0.0.1:8181
	Path    string // for example authz/allow
	Client  *http.Client
}

// ErrUndefined is returned when OPA answers without a result (undefined).
var ErrUndefined = errors.New("httpguard: OPA decision is undefined")

// Decide implements authz.Decider. An undefined result is an error, which the
// PEP turns into a denial.
func (o OPA) Decide(ctx context.Context, r authz.Request) (authz.Decision, error) {
	body, err := json.Marshal(map[string]any{"input": r})
	if err != nil {
		return authz.Decision{}, err
	}
	hr, err := http.NewRequestWithContext(ctx, http.MethodPost, o.BaseURL+"/v1/data/"+o.Path, bytes.NewReader(body))
	if err != nil {
		return authz.Decision{}, err
	}
	hr.Header.Set("Content-Type", "application/json")
	resp, err := o.Client.Do(hr)
	if err != nil {
		return authz.Decision{}, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return authz.Decision{}, fmt.Errorf("httpguard: OPA status %d", resp.StatusCode)
	}
	var out struct {
		Result *bool `json:"result"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
		return authz.Decision{}, err
	}
	if out.Result == nil {
		return authz.Decision{}, ErrUndefined
	}
	return authz.Decision{Allow: *out.Result, Reason: "opa " + o.Path}, nil
}
go
package httpguard

import (
	"context"
	"errors"
	"net/http"
	"net/http/httptest"
	"testing"
	"time"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

func extract(hr *http.Request) (authz.Request, error) {
	user := hr.Header.Get("X-User")
	if user == "" {
		return authz.Request{}, errors.New("no user")
	}
	return authz.Request{
		Subject: user, SubjectTenant: hr.Header.Get("X-Tenant"), Action: "read",
		Resource: authz.Resource{Type: "doc", ID: "7", Tenant: "acme"},
	}, nil
}

func call(h http.Handler, user, tenant string) int {
	r := httptest.NewRequest("GET", "/docs/7", nil)
	if user != "" {
		r.Header.Set("X-User", user)
	}
	r.Header.Set("X-Tenant", tenant)
	w := httptest.NewRecorder()
	h.ServeHTTP(w, r)
	return w.Code
}

func TestStatusCodes(t *testing.T) {
	ok := authz.DeciderFunc(func(_ context.Context, r authz.Request) (authz.Decision, error) {
		return authz.Decision{Allow: r.Subject == "ana"}, nil
	})
	next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(200) })
	h := Enforce(ok, extract, nil, next)
	for _, c := range []struct {
		user, tenant string
		want         int
	}{{"", "acme", 401}, {"ana", "acme", 200}, {"bob", "acme", 403}, {"ana", "globex", 404}} {
		if got := call(h, c.user, c.tenant); got != c.want {
			t.Errorf("%q/%s: got %d want %d", c.user, c.tenant, got, c.want)
		}
	}
}

func TestFailClosed(t *testing.T) {
	broken := authz.DeciderFunc(func(context.Context, authz.Request) (authz.Decision, error) {
		return authz.Decision{Allow: true}, errors.New("pdp down")
	})
	called := false
	next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true })
	if got := call(Enforce(broken, extract, nil, next), "ana", "acme"); got != 503 || called {
		t.Fatalf("got %d called=%v; an error must never reach the handler", got, called)
	}
}

func TestCacheTTLs(t *testing.T) {
	now := time.Unix(0, 0)
	calls := 0
	inner := authz.DeciderFunc(func(context.Context, authz.Request) (authz.Decision, error) {
		calls++
		return authz.Decision{Allow: true}, nil
	})
	c := &Cache{Inner: inner, PositiveTTL: 30 * time.Second, NegativeTTL: 5 * time.Second, Now: func() time.Time { return now }}
	r := authz.Request{Subject: "ana", Action: "read", Resource: authz.Resource{Type: "doc", ID: "1"}}
	for i := 0; i < 3; i++ {
		_, _ = c.Decide(context.Background(), r)
	}
	now = now.Add(31 * time.Second)
	_, _ = c.Decide(context.Background(), r)
	if calls != 2 || c.Hits != 2 {
		t.Fatalf("calls=%d hits=%d, want 2 and 2", calls, c.Hits)
	}
}

func TestOPAClient(t *testing.T) {
	srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/v1/data/authz/allow" {
			http.NotFound(w, r)
			return
		}
		_, _ = w.Write([]byte(`{"result": true}`))
	}))
	defer srv.Close()
	o := OPA{BaseURL: srv.URL, Path: "authz/allow", Client: srv.Client()}
	d, err := o.Decide(context.Background(), authz.Request{Subject: "ana"})
	if err != nil || !d.Allow {
		t.Fatalf("got %+v %v", d, err)
	}
	o.Path = "authz/missing"
	if _, err := o.Decide(context.Background(), authz.Request{}); err == nil {
		t.Fatal("a 404 must be an error, not an allow")
	}
}

نمونه: آداپتورهای Cedar و OpenFGA ​

go
// Package cedarx wraps cedar-go (the Cedar policy language, Go implementation)
// as an authz.Decider. Cedar is default-deny, and any matching forbid policy
// overrides every permit.
package cedarx

import (
	"context"

	"github.com/cedar-policy/cedar-go"
	"github.com/cedar-policy/cedar-go/types"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

// Decider evaluates a parsed Cedar policy set against an entity store.
type Decider struct {
	Policies *cedar.PolicySet
	// Entities returns the entity data (attributes and parents) for a request:
	// this is where a policy information point (PIP) plugs in.
	Entities func(authz.Request) types.EntityGetter
}

// Parse reads Cedar policy text.
func Parse(name string, text []byte) (*cedar.PolicySet, error) {
	return cedar.NewPolicySetFromBytes(name, text)
}

// Decide implements authz.Decider.
func (d Decider) Decide(_ context.Context, r authz.Request) (authz.Decision, error) {
	req := cedar.Request{
		Principal: cedar.NewEntityUID("User", cedar.String(r.Subject)),
		Action:    cedar.NewEntityUID("Action", cedar.String(r.Action)),
		Resource:  cedar.NewEntityUID(cedar.EntityType(r.Resource.Type), cedar.String(r.Resource.ID)),
		Context:   cedar.NewRecord(cedar.RecordMap{"hour": cedar.String(r.Env["hour"])}),
	}
	ok, diag := cedar.Authorize(d.Policies, d.Entities(r), req)
	out := authz.Decision{Allow: bool(ok == cedar.Allow)}
	for _, reason := range diag.Reasons {
		out.Policies = append(out.Policies, string(reason.PolicyID))
	}
	if out.Allow {
		out.Reason = "permitted by Cedar"
	} else {
		out.Reason = "denied by Cedar (default deny or a forbid)"
	}
	return out, nil
}
go
package cedarx

import (
	"context"
	"os"
	"testing"

	"github.com/cedar-policy/cedar-go"
	"github.com/cedar-policy/cedar-go/types"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

const policies = `
@id("dept-read")
permit (principal, action == Action::"read", resource)
when { principal.department == resource.department };

@id("tenant-wall")
forbid (principal, action, resource)
unless { principal.tenant == resource.tenant };
`

func entities(authz.Request) types.EntityGetter {
	rec := func(m map[string]string) types.Record {
		rm := types.RecordMap{}
		for k, v := range m {
			rm[types.String(k)] = types.String(v)
		}
		return types.NewRecord(rm)
	}
	ana := cedar.NewEntityUID("User", "ana")
	doc := cedar.NewEntityUID("Document", "1")
	other := cedar.NewEntityUID("Document", "2")
	return types.EntityMap{
		ana:   {UID: ana, Attributes: rec(map[string]string{"department": "finance", "tenant": "acme"})},
		doc:   {UID: doc, Attributes: rec(map[string]string{"department": "finance", "tenant": "acme"})},
		other: {UID: other, Attributes: rec(map[string]string{"department": "finance", "tenant": "globex"})},
	}
}

func TestCedarDecisions(t *testing.T) {
	ps, err := Parse("policies.cedar", []byte(policies))
	if err != nil {
		t.Fatal(err)
	}
	d := Decider{Policies: ps, Entities: entities}
	for _, c := range []struct {
		doc, action string
		want        bool
	}{{"1", "read", true}, {"1", "delete", false}, {"2", "read", false}} {
		got, err := d.Decide(context.Background(), authz.Request{
			Subject: "ana", Action: c.action, Resource: authz.Resource{Type: "Document", ID: c.doc},
		})
		if err != nil || got.Allow != c.want {
			t.Errorf("doc %s %s: allow=%v want %v (%s)", c.doc, c.action, got.Allow, c.want, got.Reason)
		}
	}
}

// The policy file shown in the chapter must parse with the real Cedar parser.
func TestChapterPolicyFileParses(t *testing.T) {
	b, err := os.ReadFile("../../policies/documents.cedar")
	if err != nil {
		t.Fatal(err)
	}
	if _, err := Parse("documents.cedar", b); err != nil {
		t.Fatal(err)
	}
}
go
// Package fga calls an OpenFGA server (a Zanzibar-style ReBAC service) through
// the official Go SDK. It is compile-checked against the SDK, and the Checker
// interface lets the decider be tested without a server.
package fga

import (
	"context"
	"fmt"

	openfga "github.com/openfga/go-sdk"
	"github.com/openfga/go-sdk/client"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

// Checker is the one SDK call the decider needs.
type Checker interface {
	Check(ctx context.Context, user, relation, object string, higherConsistency bool) (bool, error)
}

// SDK implements Checker with the OpenFGA Go SDK.
type SDK struct{ C *client.OpenFgaClient }

// NewSDK builds a client for one store and one pinned authorization model.
func NewSDK(apiURL, storeID, modelID string) (*SDK, error) {
	c, err := client.NewSdkClient(&client.ClientConfiguration{
		ApiUrl:               apiURL,
		StoreId:              storeID,
		AuthorizationModelId: modelID,
	})
	if err != nil {
		return nil, err
	}
	return &SDK{C: c}, nil
}

// Check calls POST /stores/{id}/check. HIGHER_CONSISTENCY skips the cache.
func (s *SDK) Check(ctx context.Context, user, relation, object string, higher bool) (bool, error) {
	opts := client.ClientCheckOptions{}
	if higher {
		opts.Consistency = openfga.CONSISTENCYPREFERENCE_HIGHER_CONSISTENCY.Ptr()
	}
	resp, err := s.C.Check(ctx).
		Body(client.ClientCheckRequest{User: user, Relation: relation, Object: object}).
		Options(opts).
		Execute()
	if err != nil {
		return false, err
	}
	return resp.GetAllowed(), nil
}

// Decider maps an authz.Request to an OpenFGA check. The action is the
// relation name (for example "viewer"), the resource is "type:id".
type Decider struct {
	Checker Checker
	// StrongActions need read-after-write consistency, for example after a
	// share dialog or a permission removal.
	StrongActions map[string]bool
}

// Decide implements authz.Decider.
func (d Decider) Decide(ctx context.Context, r authz.Request) (authz.Decision, error) {
	obj := r.Resource.Type + ":" + r.Resource.ID
	ok, err := d.Checker.Check(ctx, "user:"+r.Subject, r.Action, obj, d.StrongActions[r.Action])
	if err != nil {
		return authz.Decision{}, fmt.Errorf("fga check %s#%s: %w", obj, r.Action, err)
	}
	return authz.Decision{Allow: ok, Reason: "openfga check " + obj + "#" + r.Action}, nil
}
go
package fga

import (
	"context"
	"testing"

	"academy/authorization-rbac-abac-zero-trust/authz"
)

type fake map[string]bool

func (f fake) Check(_ context.Context, user, rel, obj string, _ bool) (bool, error) {
	return f[user+"|"+rel+"|"+obj], nil
}

func TestDeciderBuildsTuple(t *testing.T) {
	d := Decider{Checker: fake{"user:ana|viewer|doc:1": true}}
	got, _ := d.Decide(context.Background(), authz.Request{Subject: "ana", Action: "viewer", Resource: authz.Resource{Type: "doc", ID: "1"}})
	if !got.Allow {
		t.Fatal("expected allow")
	}
	got, _ = d.Decide(context.Background(), authz.Request{Subject: "bob", Action: "viewer", Resource: authz.Resource{Type: "doc", ID: "1"}})
	if got.Allow {
		t.Fatal("expected deny")
	}
}

func TestSDKConstructs(t *testing.T) {
	if _, err := NewSDK("http://127.0.0.1:8080", "01HXXXXXXXXXXXXXXXXXXXXXXX", ""); err != nil {
		t.Fatal(err)
	}
}

زاویهٔ Go ​

Go در کتابخانهٔ استاندارد چارچوب مجوزدهی ندارد، پس الگو یک رابط کوچک (Decider) و middleware است. PEP را در middleware ‏net/http (یا interceptor در gRPC) بگذارید، context.Context درخواست را به PDP بدهید تا timeout منتقل شود، روی هر خطا fail closed کنید و ماتریس را با تست جدولی بسنجید. cedar-go Cedar را درون‌فرایندی اجرا می‌کند (تصمیم در حد میکروثانیه، بدون شبکه)، OPA معمولاً sidecar است که با REST Data API صدا زده می‌شود و OpenFGA یا SpiceDB سرویس مرکزی‌اند که با SDK صدا می‌خورند؛ آداپتور fga روی SDK واقعی کامپایل می‌شود و از طریق درز Checker تست واحد شده، ولی روی سرور زنده اجرا نشده است.

Laravel ​

Laravel 13 PEP و یک PDP کوچک دارد: Gate (closureها و قلاب Gate::before)، Policyها (یک کلاس برای هر مدل، کشف با قرارداد نام یا attribute ‏#[UsePolicy])، Gate::authorize در کد، alias ‏can روی routeها، @can در Blade و Response::deny / denyAsNotFound برای دلیل و وضعیت. برای نقش و مجوز به‌صورت داده، spatie/laravel-permission جدول‌ها، trait ‏HasRoles و یکپارچگی با Gate را اضافه می‌کند؛ نسخه‌های 7 و 8 بسته Laravel 12 و 13 را پشتیبانی می‌کنند.

نمونه: Policy که همان قاعدهٔ ABAC هم هست ​

php
<?php

namespace App\Policies;

use App\Models\Document;
use App\Models\User;
use Illuminate\Auth\Access\Response;

class DocumentPolicy
{
    // Runs before every other method of this policy. Returning null falls through.
    public function before(User $user, string $ability): ?bool
    {
        return $user->suspended_at !== null ? false : null;
    }

    public function viewAny(User $user): bool
    {
        return $user->can('documents.read');
    }

    // ABAC rule: same tenant, same department, business hours, managed device for confidential files.
    public function view(User $user, Document $document): Response
    {
        if ($user->tenant_id !== $document->tenant_id) {
            return Response::denyAsNotFound();
        }

        if ($document->classification === 'confidential' && ! request()->attributes->get('device_managed', false)) {
            return Response::deny('Confidential documents need a managed device.');
        }

        $hour = (int) now()->setTimezone($user->tenant->timezone ?? 'UTC')->format('G');

        return $user->department === $document->department && $hour >= 8 && $hour < 18
            ? Response::allow()
            : Response::deny('Outside department or business hours.');
    }

    public function update(User $user, Document $document): bool
    {
        return $user->tenant_id === $document->tenant_id
            && ($user->id === $document->owner_id || $user->can('documents.edit-any'));
    }

    public function delete(User $user, Document $document): bool
    {
        return $this->update($user, $document) && $user->can('documents.delete');
    }
}
php
<?php

namespace App\Models;

use App\Policies\DocumentPolicy;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

#[UsePolicy(DocumentPolicy::class)]
class Document extends Model
{
    protected $fillable = ['tenant_id', 'owner_id', 'department', 'classification', 'title'];

    // Tenant id in every query: a global scope so a forgotten where() cannot leak rows.
    protected static function booted(): void
    {
        static::addGlobalScope('tenant', function (Builder $query) {
            if ($tenantId = app()->bound('tenant.id') ? app('tenant.id') : null) {
                $query->where($query->getModel()->getTable().'.tenant_id', $tenantId);
            }
        });

        static::creating(function (Document $document) {
            $document->tenant_id ??= app('tenant.id');
        });
    }
}

نمونه: Gate::before، یک Gate ساده و یک Gate برای ReBAC ​

php
<?php

namespace App\Providers;

use App\Authz\RelationshipChecker;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Policies for App\Models\Document are found by naming convention or #[UsePolicy].

        // Super-admin: the standard Gate::before pattern. A null return falls through to the real checks.
        Gate::before(function (User $user, string $ability) {
            return $user->hasRole('super-admin') ? true : null;
        });

        // A plain Gate for something that is not tied to one model.
        Gate::define('approve-invoice', function (User $user, int $amountCents) {
            return $user->can('invoices.approve') && $amountCents <= $user->approval_limit_cents;
        });

        // ReBAC through a Gate: "share" is allowed when the user holds the relation on the object.
        Gate::define('rebac', function (User $user, string $relation, string $objectType, string $objectId) {
            return app(RelationshipChecker::class)->check($user->tenant_id, $objectType, $objectId, $relation, $user->id);
        });
    }
}
php
<?php

namespace App\Authz;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;

// A small ReBAC checker over the relation_tuples table: a direct tuple, or one userset hop.
class RelationshipChecker
{
    public function check(int $tenantId, string $type, string $id, string $relation, int $userId): bool
    {
        // Decision cache: short, per tuple version. Bump the version key on every tuple write.
        $version = Cache::get("authz:version:{$tenantId}", 0);
        $key = "authz:{$version}:{$tenantId}:{$type}:{$id}:{$relation}:{$userId}";

        return Cache::remember($key, 30, fn () => $this->evaluate($tenantId, $type, $id, $relation, $userId));
    }

    public function bump(int $tenantId): void
    {
        Cache::add("authz:version:{$tenantId}", 0);
        Cache::increment("authz:version:{$tenantId}");
    }

    private function evaluate(int $tenantId, string $type, string $id, string $relation, int $userId): bool
    {
        $direct = DB::table('relation_tuples')
            ->where(['tenant_id' => $tenantId, 'object_type' => $type, 'object_id' => $id, 'relation' => $relation])
            ->where(['subject_type' => 'user', 'subject_id' => (string) $userId, 'subject_relation' => ''])
            ->exists();

        if ($direct) {
            return true;
        }

        // Userset hop: object#relation@group:x#member and group:x#member@user
        return DB::table('relation_tuples as d')
            ->join('relation_tuples as g', function ($join) {
                $join->on('g.tenant_id', '=', 'd.tenant_id')
                    ->on('g.object_type', '=', 'd.subject_type')
                    ->on('g.object_id', '=', 'd.subject_id')
                    ->on('g.relation', '=', 'd.subject_relation');
            })
            ->where(['d.tenant_id' => $tenantId, 'd.object_type' => $type, 'd.object_id' => $id, 'd.relation' => $relation])
            ->where(['g.subject_type' => 'user', 'g.subject_id' => (string) $userId, 'g.subject_relation' => ''])
            ->exists();
    }
}

نمونه: route، controller و middleware مستاجر ​

php
<?php

use App\Http\Controllers\DocumentController;
use App\Http\Middleware\SetTenant;
use App\Models\Document;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth', SetTenant::class])->group(function () {
    Route::get('/documents', [DocumentController::class, 'index']);
    Route::get('/documents/{document}', [DocumentController::class, 'show'])->middleware('can:view,document');
    Route::put('/documents/{document}', [DocumentController::class, 'update'])->middleware('can:update,document');
    // A class-level ability without a model instance:
    Route::post('/documents', fn () => response()->noContent(201))->middleware('can:create,'.Document::class);
    // A permission-name check, which works because spatie registers permissions with the Gate:
    Route::get('/reports', fn () => response()->json([]))->middleware('can:reports.read');
});
php
<?php

namespace App\Http\Controllers;

use App\Models\Document;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class DocumentController extends Controller
{
    public function index()
    {
        Gate::authorize('viewAny', Document::class);

        return Document::query()->latest()->paginate(); // tenant scope is added by the model
    }

    public function show(Document $document)
    {
        // Throws AuthorizationException (403) or a 404 when the policy used denyAsNotFound().
        Gate::authorize('view', $document);

        return $document;
    }

    public function update(Request $request, Document $document)
    {
        // The route also carries can:update,document; this line is the second, in-code check.
        Gate::authorize('update', $document);
        $document->update($request->validate(['title' => 'required|string|max:200']));

        return $document;
    }

    public function share(Request $request, Document $document)
    {
        // Gate::inspect keeps the reason for the audit log.
        $response = Gate::inspect('rebac', ['editor', 'doc', (string) $document->id]);
        logger()->info('authz.decision', [
            'ability' => 'share', 'document' => $document->id,
            'allowed' => $response->allowed(), 'message' => $response->message(),
        ]);
        abort_unless($response->allowed(), 403);

        return response()->noContent();
    }
}
php
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

// Binds the tenant of the authenticated user and tells PostgreSQL row-level security about it.
class SetTenant
{
    public function handle(Request $request, Closure $next): Response
    {
        $user = $request->user();
        abort_if($user === null, 401);

        app()->instance('tenant.id', $user->tenant_id);

        // Transaction-local setting: safe with pooled connections (see the SQL snippet).
        return DB::transaction(function () use ($user, $request, $next) {
            DB::select("select set_config('app.tenant_id', ?, true)", [(string) $user->tenant_id]);

            return $next($request);
        });
    }
}

نمونه: spatie/laravel-permission به‌عنوان store نقش‌ها ​

php
<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Permission\Traits\HasRoles;

class User extends Authenticatable
{
    // HasRoles adds assignRole(), givePermissionTo(), hasRole() and registers
    // permissions with the Gate so can() and the can: middleware understand them.
    use HasRoles;

    protected $casts = ['suspended_at' => 'datetime'];

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }
}
php
<?php

namespace App\Services;

use App\Models\User;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

// spatie/laravel-permission as the RBAC store: roles group permissions, users get roles.
class InvoiceApproval
{
    public function bootstrap(): void
    {
        $read = Permission::findOrCreate('invoices.read');
        $create = Permission::findOrCreate('invoices.create');
        $approve = Permission::findOrCreate('invoices.approve');

        Role::findOrCreate('viewer')->givePermissionTo($read);
        Role::findOrCreate('clerk')->givePermissionTo([$read, $create]);
        Role::findOrCreate('approver')->givePermissionTo([$read, $approve]);
    }

    public function assign(User $user, string $role): void
    {
        // Separation of duty is not built in: enforce it where roles are assigned.
        if ($role === 'approver' && $user->hasRole('clerk')) {
            throw new \DomainException('A clerk cannot also be an approver.');
        }
        if ($role === 'clerk' && $user->hasRole('approver')) {
            throw new \DomainException('An approver cannot also be a clerk.');
        }

        $user->assignRole($role);
    }

    public function canApprove(User $user, int $amountCents): bool
    {
        // can() goes through the Gate, so Gate::before (super-admin) applies.
        return $user->can('approve-invoice', $amountCents);
    }
}
php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('relation_tuples', function (Blueprint $table) {
            $table->unsignedBigInteger('tenant_id');
            $table->string('object_type');
            $table->string('object_id');
            $table->string('relation');
            $table->string('subject_type');
            $table->string('subject_id');
            $table->string('subject_relation')->default('');
            $table->timestampTz('created_at')->useCurrent();

            $table->primary(['tenant_id', 'object_type', 'object_id', 'relation', 'subject_type', 'subject_id', 'subject_relation'], 'relation_tuples_pk');
            // The reverse index that makes "what can this user see" cheap.
            $table->index(['tenant_id', 'subject_type', 'subject_id', 'subject_relation', 'object_type', 'relation'], 'relation_tuples_by_subject');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('relation_tuples');
    }
};
php
<?php

namespace Tests\Feature;

use App\Models\Document;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Gate;
use Tests\TestCase;

class DocumentPolicyTest extends TestCase
{
    use RefreshDatabase;

    public function test_other_tenant_gets_not_found(): void
    {
        $user = User::factory()->create(['tenant_id' => 1]);
        $document = Document::factory()->create(['tenant_id' => 2]);

        $response = Gate::forUser($user)->inspect('view', $document);

        $this->assertTrue($response->denied());
        $this->assertSame(404, $response->status());
    }

    public function test_owner_can_update_and_stranger_cannot(): void
    {
        $owner = User::factory()->create(['tenant_id' => 1]);
        $stranger = User::factory()->create(['tenant_id' => 1]);
        $document = Document::factory()->create(['tenant_id' => 1, 'owner_id' => $owner->id]);

        $this->assertTrue(Gate::forUser($owner)->allows('update', $document));
        $this->assertTrue(Gate::forUser($stranger)->denies('update', $document));
    }

    public function test_suspended_user_is_denied_everything_by_policy_before(): void
    {
        $user = User::factory()->create(['tenant_id' => 1, 'suspended_at' => now()]);
        $document = Document::factory()->create(['tenant_id' => 1, 'owner_id' => $user->id]);

        $this->assertTrue(Gate::forUser($user)->denies('update', $document));
    }
}

زاویهٔ Laravel ​

Policy را برای قاعده‌های شیء (لایهٔ ABAC)، مجوزهای spatie را برای اینکه چه کسی چه توانایی‌ای دارد (لایهٔ RBAC) و چک یا سرویس ReBAC را برای اشتراک‌گذاری (tuple) به کار ببرید. middleware ‏can:update,document روی route اولین PEP است؛ Gate::authorize داخل controller دومی است و وقتی همان کد از job یا دستور console صدا زده شود هم محافظ می‌ماند. توصیهٔ مستند spatie این است که super-admin را با Gate::before یا Gate::after حل کنید و همه‌جای دیگر مجوز را (can()) چک کنید نه نقش را؛ بسته هشدار می‌دهد صدا زدن مستقیم hasPermissionTo() از Gate رد نمی‌شود، پس میان‌بُر super-admin آنجا اعمال نمی‌شود. از before مقدار null بدهید تا ادامه یابد؛ false از before در policy همه چیز را رد می‌کند و قاعدهٔ کاربر تعلیق‌شده همین‌طور کار می‌کند. global scopeهای Eloquent (scope مستاجر) روی queryهای DB::table() اعمال نمی‌شوند، پس پشتیبان row-level security در SQL مهم است. فایل‌های PHP فقط با php -l بررسی نحوی شده‌اند: برش‌هایی‌اند که یک برنامهٔ استاندارد Laravel 13 با migration منتشرشدهٔ spatie را فرض می‌کنند؛ تست‌های Laravel اجرا نشده‌اند.

SQL: نقش، مجوز و relation tuple ​

sql
-- RBAC with a hierarchy and separation of duty, plus ReBAC tuples, in PostgreSQL.
CREATE TABLE tenants (id bigint PRIMARY KEY, name text NOT NULL);

CREATE TABLE users (
  id        bigint PRIMARY KEY,
  tenant_id bigint NOT NULL REFERENCES tenants(id),
  email     text   NOT NULL,
  UNIQUE (tenant_id, email)
);

CREATE TABLE roles (
  id        bigint PRIMARY KEY,
  tenant_id bigint NOT NULL REFERENCES tenants(id),
  name      text   NOT NULL,
  UNIQUE (tenant_id, name)
);

CREATE TABLE permissions (
  id   bigint PRIMARY KEY,
  name text NOT NULL UNIQUE            -- 'invoice:read', 'invoice:approve'
);

CREATE TABLE role_permissions (
  role_id       bigint REFERENCES roles(id) ON DELETE CASCADE,
  permission_id bigint REFERENCES permissions(id) ON DELETE CASCADE,
  PRIMARY KEY (role_id, permission_id)
);

-- Hierarchy: senior inherits everything junior can do.
CREATE TABLE role_inherits (
  senior_id bigint REFERENCES roles(id) ON DELETE CASCADE,
  junior_id bigint REFERENCES roles(id) ON DELETE CASCADE,
  PRIMARY KEY (senior_id, junior_id),
  CHECK (senior_id <> junior_id)
);

CREATE TABLE user_roles (
  user_id    bigint REFERENCES users(id) ON DELETE CASCADE,
  role_id    bigint REFERENCES roles(id) ON DELETE CASCADE,
  granted_by bigint REFERENCES users(id),
  granted_at timestamptz NOT NULL DEFAULT now(),
  expires_at timestamptz,               -- time-boxed grants
  PRIMARY KEY (user_id, role_id)
);

-- Static separation of duty: no user may hold both roles of a pair.
CREATE TABLE ssd_pairs (
  role_a bigint REFERENCES roles(id),
  role_b bigint REFERENCES roles(id),
  PRIMARY KEY (role_a, role_b),
  CHECK (role_a < role_b)
);

-- ReBAC: Zanzibar relation tuples  object#relation@subject
CREATE TABLE relation_tuples (
  tenant_id        bigint NOT NULL,
  object_type      text   NOT NULL,
  object_id        text   NOT NULL,
  relation         text   NOT NULL,
  subject_type     text   NOT NULL,
  subject_id       text   NOT NULL,
  subject_relation text   NOT NULL DEFAULT '',   -- '' = plain subject, 'member' = userset
  created_at       timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (tenant_id, object_type, object_id, relation, subject_type, subject_id, subject_relation)
);
-- Reverse lookup: "which objects can this subject reach" (the listing problem).
CREATE INDEX relation_tuples_by_subject
  ON relation_tuples (tenant_id, subject_type, subject_id, subject_relation, object_type, relation);

-- Tenant isolation as a database backstop (PostgreSQL row-level security).
CREATE TABLE invoices (
  id        bigint PRIMARY KEY,
  tenant_id bigint NOT NULL REFERENCES tenants(id),
  owner_id  bigint NOT NULL REFERENCES users(id),
  amount    numeric(12,2) NOT NULL
);
ALTER TABLE invoices ENABLE ROW LEVEL SECURITY;
ALTER TABLE invoices FORCE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON invoices
  USING (tenant_id = current_setting('app.tenant_id')::bigint)
  WITH CHECK (tenant_id = current_setting('app.tenant_id')::bigint);
sql
-- 1. Effective permissions of a user: roles, then every junior role reachable
--    through the hierarchy (recursive CTE), then their permissions.
WITH RECURSIVE held AS (
  SELECT role_id FROM user_roles
   WHERE user_id = $1 AND (expires_at IS NULL OR expires_at > now())
  UNION
  SELECT ri.junior_id FROM role_inherits ri JOIN held h ON h.role_id = ri.senior_id
)
SELECT DISTINCT p.name
  FROM held h
  JOIN role_permissions rp ON rp.role_id = h.role_id
  JOIN permissions p       ON p.id = rp.permission_id
 ORDER BY p.name;

-- 2. A single check: does user $1 hold permission $2?
WITH RECURSIVE held AS (
  SELECT role_id FROM user_roles
   WHERE user_id = $1 AND (expires_at IS NULL OR expires_at > now())
  UNION
  SELECT ri.junior_id FROM role_inherits ri JOIN held h ON h.role_id = ri.senior_id
)
SELECT EXISTS (
  SELECT 1 FROM held h
  JOIN role_permissions rp ON rp.role_id = h.role_id
  JOIN permissions p ON p.id = rp.permission_id AND p.name = $2
);

-- 3. Static separation of duty at write time: refuse a grant that completes a pair.
SELECT 1
  FROM ssd_pairs s
 WHERE ($2 = s.role_a AND EXISTS (SELECT 1 FROM user_roles WHERE user_id = $1 AND role_id = s.role_b))
    OR ($2 = s.role_b AND EXISTS (SELECT 1 FROM user_roles WHERE user_id = $1 AND role_id = s.role_a));

-- 4. ReBAC direct check: is user $3 a direct subject of doc $2 with relation 'viewer'?
SELECT EXISTS (
  SELECT 1 FROM relation_tuples
   WHERE tenant_id = $1 AND object_type = 'doc' AND object_id = $2 AND relation = 'viewer'
     AND subject_type = 'user' AND subject_id = $3 AND subject_relation = ''
);

-- 5. ReBAC one userset hop: viewer through a group the user belongs to.
SELECT EXISTS (
  SELECT 1
    FROM relation_tuples d
    JOIN relation_tuples g
      ON g.tenant_id = d.tenant_id
     AND g.object_type = d.subject_type AND g.object_id = d.subject_id
     AND g.relation = d.subject_relation
   WHERE d.tenant_id = $1 AND d.object_type = 'doc' AND d.object_id = $2 AND d.relation = 'viewer'
     AND g.subject_type = 'user' AND g.subject_id = $3 AND g.subject_relation = ''
);

-- 6. Listing "which documents can user $2 see" for direct and group grants,
--    served by the reverse index relation_tuples_by_subject.
SELECT d.object_id
  FROM relation_tuples d
 WHERE d.tenant_id = $1 AND d.object_type = 'doc' AND d.relation = 'viewer'
   AND ((d.subject_type = 'user' AND d.subject_id = $2 AND d.subject_relation = '')
     OR EXISTS (SELECT 1 FROM relation_tuples g
                 WHERE g.tenant_id = d.tenant_id
                   AND g.object_type = d.subject_type AND g.object_id = d.subject_id
                   AND g.relation = d.subject_relation
                   AND g.subject_type = 'user' AND g.subject_id = $2 AND g.subject_relation = ''));

-- 7. Row-level security: set the tenant per transaction, never per session
--    on a pooled connection.
BEGIN;
SELECT set_config('app.tenant_id', '42', true);   -- true = local to this transaction
SELECT * FROM invoices;                           -- only tenant 42 rows
COMMIT;
sql
-- Quick sanity check of the reverse index: the plan should use relation_tuples_by_subject
EXPLAIN SELECT object_id FROM relation_tuples
 WHERE tenant_id = 42 AND subject_type = 'user' AND subject_id = '7'
   AND subject_relation = '' AND object_type = 'doc' AND relation = 'viewer';
Queryپرسششکل هزینه
1مجوزهای مؤثر یک کاربرCTE بازگشتی روی سلسله‌مراتب؛ نتیجه را برای هر کاربر کش کنید
2آیا کاربر یک مجوز را داردهمان CTE با EXISTS
3آیا این grant separation of duties را می‌شکنددو EXISTS؛ داخل تراکنش grant اجرا شود
4چک مستقیم ReBACیک جست‌وجوی کلید اصلی
5یک hop از usersetیک join روی پیشوند کلید اصلی
6فهرست آنچه کاربر می‌بیند (مستقیم و گروهی)اسکن بازهٔ ایندکس روی reverse index به‌علاوهٔ join گروه
7جداسازی مستاجرplanner شرط policy را به هر query روی جدول اضافه می‌کند

تودرتویی عمیق‌تر (گروه داخل گروه، پوشه داخل پوشه) query 5 را به CTE بازگشتی با حد عمق تبدیل می‌کند؛ از آن نقطه موتور اختصاصی (OpenFGA، SpiceDB) از نگهداری SQL ارزان‌تر است.

حل مسئله‌های کلاسیک ​

مسئلهراه‌حلچطورمزیتهزینه یا محدودیت
IDOR: کاربر id را در URL عوض می‌کندچک سطح شیء در هر دسترسیچک Policy یا ReBAC با خود شیء، نه فقط نقشکلاس اول OWASP را می‌بنددیک فراخوانی بیشتر برای هر شیء
Role explosionویژگی یا رابطه اضافه کنیدقاعدهٔ ABAC یا tuple در ReBAC به‌جای نقش جدیدنقش کمترتست سیاست لازم است
مجوز لغوشده هنوز کار می‌کندTTL کوتاه به‌علاوهٔ کلید کش نسخه‌دار، zookie برای محتوابا هر نوشتن نسخه را بالا ببرید؛ zookie را پاس بدهیدکهنگی کران‌دارپیچیدگی cache
«این کاربر چه چیزی می‌بیند؟» کند استReverse index یا ListObjectsrelation_tuples_by_subject، LookupResources در SpiceDBیک queryهزینهٔ نوشتن ایندکس
super-admin همه‌جاGate::before برای نقش true می‌دهدجاهای دیگر مجوز را چک کنیدیک جاممیزی و لاگ استفاده
نشت بین مستاجرهامستاجر در سیاست، scope و row-level securityسه لایهدفاع در عمقتله‌های pool و دورزدن مالک
Confused deputy (سرویس با حقوق پهن خودش کار می‌کند)کاربر نهایی را به‌عنوان subject منتقل کنیدهویت را پاس بدهید و در سرویس داده چک کنیدleast privilegeلوله‌کشی
قطعی موتور سیاستFail closed؛ مثبت‌ها را کوتاه کش کنید؛ قاعده‌های حیاتی را embed کنیدCedar یا کتابخانه درون‌فرایندی برای مسیرهای اصلیایمنیبعضی قابلیت‌ها در دسترس نیستند
حساب‌های سرویس بیش‌ازحد پهنهویت جدا برای هر سرویس و grant باریکهویت mTLS به‌علاوهٔ سیاست meshleast privilegeهویت‌های زیاد برای مدیریت

رفع لغوِ کهنه، گام‌به‌گام ​

text
     t     Event                                          Cache TTL 30 s     With versioned key
1    0     Bob viewer of doc:7 (cached allow, expires 30)
2    10    admin deletes tuple doc:7#viewer@bob           still allow        key version bumped
3    11    Bob opens doc:7                                ALLOW (stale)      cache miss -> PDP -> DENY
4    31    TTL expired                                    DENY               DENY

انتخاب ​

What does the decision depend on?Job functionadmin, clerk, auditorAttributes and contextdepartment, device, hour, amountRelationships to objectsowner, shared with, member of parentRBACSpatie, Gates, role tablesABACOPA, Cedar, Policies, XACMLReBACSpiceDB, OpenFGA, Keto, PermifyCombine: role gate, attribute rule, relationship check, default deny

کدام مدل برای کدام محصول ​

نوع محصولمدل اصلیاضافه کنیددلیلپرهیز
ابزار مدیریتی داخلی، ۳ نقشRBAC (Gate در Laravel به‌علاوهٔ spatie)Policy برای قاعده‌های شیءنقش کم، ممیزی آسانموتور سیاست
برنامهٔ مصرف‌کننده (پروفایل، پست)قاعده‌های مالکیت در Policyrate limit، relation کاربر مسدود«مالک یا عمومی» سادهنقش برای هر کاربر
B2B SaaS (سازمان، پروژه)RBAC برای هر مستاجر (نقش سازمانی) به‌علاوهٔ جداسازی مستاجرReBAC برای اشتراک پروژه و منبعنقش سازمانی کم است؛ اشتراک رابطه‌ای استنقش سراسری بدون مستاجر
اشتراک سند، پوشه، لینکReBAC (OpenFGA، SpiceDB)ویژگی برای انقضای لینکارث‌بری و گروه تودرتوجدول ACL برای هر سند با N join
داده‌های مقرراتی (سلامت، مالی)ABAC (Cedar، OPA)RBAC برای دسترسی درشت، audit logقاعده‌های زمینه (هدف، دستگاه، زمان)چک‌های آزاد در کد
پلتفرم میکروسرویسسیاست mesh به‌علاوهٔ authz در هر سرویسsidecar ‏OPA، هویت mTLSهویت سرویس و Zero Trustاعتماد به شبکهٔ داخلی
API عمومی برای شرکاscopeهای OAuth به‌علاوهٔ چک هر منبعrate limit برای هر clientتفویض به‌علاوهٔ چک شیءscope به‌عنوان تنها چک

کدام موتور ​

وضعیتانتخابچرا
مونولیت Laravel، نقش و PolicyGate، Policy، spatieداخلی، قابل‌تست، سرویس جدید نمی‌خواهد
چند زبان، سیاست مرکزی، ویژگیOPA (Rego)یک موتور سیاست، sidecar یا کتابخانه
درون‌فرایندی، تحلیل‌پذیر، default-denyCedar (cedar-go، Verified Permissions)اعتبارسنجی schema، forbid می‌برد
اشتراک و گروه تودرتو در مقیاسOpenFGA یا SpiceDBtuple، ListObjects، توکن سازگاری
یک دیتابیس، جداسازی ساده مستاجرRLS در PostgreSQL به‌علاوهٔ لایهٔ سیاستپشتیبان برای هر مسیر query

در معماری: از یک فرایند تا سیستم توزیع‌شده ​

مونولیت: یک فرایند، یک دیتابیس ​

مونولیت Laravel با Gate و Policy کافی است: یک PEP (middleware ‏can)، یک PDP (کلاس‌های Policy)، یک PIP (مدل‌های Eloquent)، یک PAP (کد در Git). scope مستاجر را در مدل نگه دارید، وقتی فهرست مجوزها بزرگ شد نقش‌های spatie را اضافه کنید و زیرش row-level security را به‌عنوان پشتیبان بگذارید.

مونولیت ماژولار: مرز بدون شبکه ​

هر ماژول سیاست‌های خودش را دارد (billing دربارهٔ فاکتور تصمیم می‌گیرد، documents دربارهٔ سند) و یک متد مجوزدهی را به‌عنوان API عمومی‌اش می‌دهد؛ هیچ ماژولی جدول‌های نقش ماژول دیگر را نمی‌خواند. نوع مشترک Request و Decision (مثل authz.go) ماژول‌ها را جدا نگه می‌دارد و ماژولی که رابطه‌های ماژول دیگر را می‌خواهد متد عمومی آن را صدا می‌زند نه جدول‌هایش را.

میکروسرویس‌ها: هر پیکان یک تصمیم است ​

text
     Caller            Hop                  Subject used            Check
1    browser           -> gateway           user (session or JWT)   authenticate; coarse scope and route check
2    gateway           -> orders service    user + service id       order policy (object, tenant)
3    orders service    -> billing service   service id (mTLS)       mesh policy: orders may call billing
4    billing service   -> data store        user id forwarded       row-level security by tenant

gateway مالکیت شیء را نمی‌داند؛ هر سرویس باید شیءها را چک کند. هویت کاربر نهایی را (نه فقط هویت سرویس) منتقل کنید تا مسئلهٔ confused deputy پیش نیاید. mesh اجرا می‌کند چه کسی می‌تواند چه کسی را صدا بزند (Service Mesh & the Sidecar Pattern، Mutual TLS)؛ سرویس اجرا می‌کند کاربر چه می‌تواند بکند (Service Communication).

داده‌های توزیع‌شده: replica، cache، regionها ​

store مجوز replicaشده همان انضباطِ هر داده replicaشده را می‌خواهد (Consistency Models): نوشتن مجوز به یک جا می‌رود و خواندنی که از محتوا محافظت می‌کند توکنی می‌خواهد که ثابت کند خواندن دست‌کم به تازگی محتواست. Zanzibar داده‌های ACL را در "tens of geographically distributed data centers" تکرار می‌کند و برای این کار zookie و timestampهای Spanner را به کار می‌برد. کش تصمیم خودش یک replica است: TTL آن تأخیر لغو شماست، پس برای هر دستهٔ منبع جدا انتخابش کنید (Caching).

مسیر مقیاس: 1x، 10x، 100x ​

بارطراحیچه عوض می‌شود
1x: یک برنامه، هزاران کاربرGate، Policy، spatie، scope مستاجرچیز بیرونی نیست
10x: مستاجر زیاد، قابلیت اشتراکجدول tuple با reverse index، کش تصمیم با کلید نسخه‌داررابطه‌ها از جدول‌های موردی بیرون می‌روند
100x: سرویس زیاد، region زیادخوشهٔ OpenFGA یا SpiceDB (یا کلاس Zanzibar)، sidecarهای OPA، zookie کنار محتواstore مرکزی رابطه، توکن سازگاری، batch check، ListObjects برای فهرست‌ها
همیشهdefault deny، audit log، تست سیاست در CIهرگز شل نمی‌شود

آزمایشگاه: سیاست، قید و یک snapshot کهنه ​

آزمایش 1: اجرای آزمایشگاه درون‌فرایندی (اجرا شده) ​

bash
cd docs/snippets/system-design/authorization-rbac-abac-zero-trust/go
go run ./cmd/lab
txt
roles needed if every combination is a role: 72
roles with 3 attribute checks instead:        3 policies
assign clerk:    <nil>
assign approver: rbac: static separation of duty violated: bob cannot also be approver
eve at stale snapshot 2: true; at zookie 3: false
ListObjects: 1001 visible documents, 1001 checks performed

چهار خط نشان می‌دهند: ۷۲ ترکیب نقش در برابر ۳ چک ویژگی؛ پیام نقض SSD؛ همان Check که در snapshot قدیمی true و در zookie false است؛ و هزینهٔ فهرست‌کردن (۱٬۰۰۱ چک نقطه‌ای برای ۱٬۰۰۱ سند)، یعنی مسئلهٔ reverse index با عدد.

آزمایش 2: تست‌های Go (اجرا شده) ​

bash
cd docs/snippets/system-design/authorization-rbac-abac-zero-trust/go
gofmt -l . && go vet ./... && go test -count=1 ./...
# ok  .../abac  ok .../cedarx  ok .../fga  ok .../httpguard  ok .../rbac  ok .../rebac

آزمایش 3: تست‌های Rego با OPA (اجرا شده) ​

bash
opa test docs/snippets/system-design/authorization-rbac-abac-zero-trust/policies -v
# data.authz_test.test_department_read_in_hours: PASS
# data.authz_test.test_other_tenant_denied: PASS
# data.authz_test.test_after_hours_denied: PASS
# PASS: 3/3

آزمایش 4: Policy در Laravel و spatie روی دیتابیس (خروجی موردانتظار؛ اجرا نشده) ​

bash
composer require spatie/laravel-permission
php artisan vendor:publish --provider="Spatie\Permission\PermissionServiceProvider"
php artisan migrate
php artisan test --filter=DocumentPolicyTest
# expected: 3 tests, 0 failures (cross-tenant gets 404, owner may update, suspended user is denied)

آزمایش 5: OpenFGA با فایل مدل (خروجی موردانتظار؛ اجرا نشده) ​

bash
fga store create --name docs
fga model write --store-id $STORE_ID --file policies/model.fga
fga tuple write --store-id $STORE_ID user:bob member group:eng
fga tuple write --store-id $STORE_ID group:eng#member viewer folder:plans
fga tuple write --store-id $STORE_ID folder:plans parent document:roadmap
fga query check --store-id $STORE_ID user:bob viewer document:roadmap
# expected: allowed: true  (via folder viewer through the parent)

بدفهمی‌های رایج ​

باورواقعیت
توکن معتبر یعنی درخواست مجاز استهویت و claimها را ثابت می‌کند؛ تصمیم شیء جداست
RBAC منسوخ استلایهٔ درشت بیشتر سیستم‌هاست؛ ABAC و ReBAC آن را ریزتر می‌کنند
ABAC یعنی نقش نداریمنقش یکی از ویژگی‌هاست
نقش بیشتر کنترل ریزتر می‌دهداز جایی به بعد role explosion و grantهای غیرقابل‌ممیزی می‌آورد
موتور سیاست درخواست را مسدود می‌کندPEP مسدود می‌کند؛ PDP فقط جواب می‌دهد
ReBAC دیتابیس گراف می‌خواهدZanzibar از tupleهای تخت در store معمولی استفاده می‌کند
eventual consistency برای مجوز اشکالی نداردACL کهنه مسئلهٔ new enemy می‌سازد
scopeهای OAuth مجوزهای کاربرندscope تفویض کاربر به client است
gateway همه چیز را مجوز می‌دهدشیءها را نمی‌شناسد؛ سرویس‌ها باید چک کنند
Zero Trust یک محصول استمجموعه‌ای از اصول است (NIST SP 800-207)؛ محصولات بخش‌هایی را پیاده می‌کنند
چک admin بدون tenant id امن استادمین مستاجر A نباید مستاجر B را بخواند
دکمه را پنهان کنی endpoint امن استسرور باید هر فراخوانی را اعمال کند

برگهٔ یادسپار ​

موضوعیادتان باشد
ترتیباول احراز هویت، بعد مجوزدهی؛ 401 در برابر 403 در برابر 404
پیش‌فرضdeny مگر قاعده‌ای اجازه دهد؛ روی خطا fail closed
PEP در برابر PDPPEP اجرا می‌کند؛ PDP تصمیم می‌گیرد؛ PIP واقعیت می‌دهد؛ PAP سیاست نگه می‌دارد
RBACمجوز را چک کنید، از طریق نقش اعطا کنید؛ نقش‌ها کم باشند
SSD در برابر DSDSSD هنگام اعطا، DSD هنگام فعال‌سازی نشست
ABACویژگی subject، resource، action، environment؛ forbid می‌برد
ReBACtuple به شکل object#relation@subject؛ rewrite rule؛ zookie برای تازگی
فهرست‌کردنمسئلهٔ reverse index؛ N چک اجرا نکنید
مستاجرهاtenant id در سیاست، scope ORM و row-level security؛ بین مستاجرها 404
Scopeاشتراک مجوز کاربر و scope client
CacheTTL پنجرهٔ لغو است؛ کلید نسخه‌دار؛ هرگز خطا را کش نکنید
ممیزیتصمیم، شناسهٔ سیاست و نسخه را لاگ کنید؛ تغییر grant را لاگ کنید
Zero Trustاعتماد از موقعیت شبکه نه؛ per-session، تأیید پیوسته، least privilege
LaravelPolicy برای شیء، spatie برای مجوز، Gate::before برای super-admin
Goرابط Decider، PEP در middleware، تست جدولی

خودآزمایی: پرسش و پاسخ ​

نمایش:
  • حیاتی تقریباً در هر مصاحبه پرسیده می‌شود
  • مهم پرتکرار؛ در سطح senior انتظار می‌رود
  • تکمیلی عمق بیشتر؛ تمایز ایجاد می‌کند

۱ — چرا JWT معتبر هم می‌تواند 403 بدهد؟ حیاتی ​

پاسخ

پاسخ: احراز هویت هویت و claimها را ثابت می‌کند؛ مجوزدهی ارزیابی می‌کند این سوژه می‌تواند این عمل را روی این منبع انجام دهد، با نقش، ویژگی یا رابطه و شاید داده‌ای تازه‌تر از توکن.

۲ — کدام جزء XACML تصمیم را اجرا می‌کند و کدام می‌گیرد؟ تکمیلی ​

پاسخ

پاسخ: PEP اجرا می‌کند (middleware، gateway، Gate)؛ PDP می‌گیرد (OPA، Cedar، SpiceDB، کلاس Policy). PIP ویژگی می‌دهد و PAP سیاست را مدیریت می‌کند.

۳ — role explosion چیست و دو راه کاهشش؟ مهم ​

پاسخ

پاسخ: یک نقش برای هر ترکیب ویژگی (۷۲ برای ۶ x ۴ x ۳). قاعدهٔ ویژگی (ABAC) یا tuple رابطه (ReBAC) اضافه کنید، از سلسله‌مراتب و چک بر پایهٔ مجوز استفاده کنید.

۴ — separation of duties ایستا در برابر پویا؟ تکمیلی ​

پاسخ

پاسخ: ایستا اجازه نمی‌دهد نقش‌های متضاد اصلاً به یک کاربر داده شود؛ پویا هر دو اعطا را اجازه می‌دهد ولی فعال‌کردن هر دو در یک نشست را ممنوع می‌کند.

۵ — doc:readme#viewer@group:eng#member یعنی چه؟ تکمیلی ​

پاسخ

پاسخ: یک relation tuple: اعضای گروه eng (یک userset) بینندگان سند readme هستند.

۶ — مسئلهٔ new enemy چیست و چه چیزی آن را درمان می‌کند؟ مهم ​

پاسخ

پاسخ: اعمال ACL کهنه روی محتوای جدید (یا نادیده‌گرفتن ترتیب به‌روزرسانی ACL) تا کاربر حذف‌شده محتوای جدید را ببیند. zookie و خواندن از snapshotی دست‌کم به تازگی نسخهٔ محتوا درمانش است.

۷ — چرا «آنچه می‌بینم را فهرست کن» از یک چک سخت‌تر است؟ مهم ​

پاسخ

پاسخ: چک از یک شیء می‌پیماید؛ فهرست‌کردن باید از کاربر برعکس بپیماید، پس reverse index، ListObjects یا LookupResources یا join در SQL می‌خواهد.

۸ — scope در OAuth و permission چطور ترکیب می‌شوند؟ حیاتی ​

پاسخ

پاسخ: دسترسی مؤثر اشتراک است: کاربر باید مجوز را داشته باشد و client باید scope را.

۹ — چه سه لایه‌ای از مستاجرها محافظت می‌کنند؟ حیاتی ​

پاسخ

پاسخ: سیاست (ناهمخوانی مستاجر forbid)، scope در ORM و row-level security دیتابیس با FORCE؛ به‌علاوهٔ 404 برای id مستاجر دیگر و tenant id در کلید cache.

۱۰ — برگرداندن null از Gate::before در Laravel چه می‌کند؟ مهم ​

پاسخ

پاسخ: به چک‌های عادی ادامه می‌دهد؛ فقط نتیجهٔ غیر null نهایی است.

۱۱ — ایده‌های NIST SP 800-207 هر کدام در یک خط؟ تکمیلی ​

پاسخ

پاسخ: اعتماد از موقعیت شبکه نه، دسترسی per-session با least privilege، سیاست پویا بر پایهٔ هویت و دستگاه و رفتار، پایش پیوستهٔ posture دارایی‌ها، اعمال سخت پیش از دسترسی، و جمع‌آوری داده برای بهتر کردن سیاست.

۱۲ — چرا PEP باید fail closed باشد؟ حیاتی ​

پاسخ

پاسخ: اگر خطا به allow تبدیل شود، مهاجمی که بتواند PDP را مختل کند دسترسی می‌گیرد؛ 503 از 200 غلط ایمن‌تر است.

واژه‌نامه ​

اصطلاحمعنی
مجوزدهی (Authorization)تصمیم‌گیری اینکه سوژه می‌تواند عملی را روی منبعی انجام دهد
کنترل دسترسی (Access control)سازوکارهایی که مجوزدهی را اعمال می‌کنند
احراز هویت (Authentication)مشخص‌کردن اینکه سوژه کیست
PEPPolicy Enforcement Point: رهگیری و اعمال
PDPPolicy Decision Point: ارزیابی سیاست‌ها
PIPPolicy Information Point: تأمین ویژگی‌ها
PAPPolicy Administration Point: مدیریت سیاست‌ها
XACMLاستاندارد XML از OASIS برای سیاست ویژگی‌محور و معماری
ALFAAbbreviated Language for Authorization، نحو فشرده روی XACML
ACLفهرست کنترل دسترسی متصل به شیء
RBACکنترل دسترسی مبتنی بر نقش
NIST RBACمدل مرجع، ANSI/INCITS 359
نقش (Role)مجموعهٔ نام‌دار مجوزها که به شغل وصل است
مجوز (Permission)عملی روی یک نوع شیء
سلسله‌مراتب نقش (Role hierarchy)نقش ارشد مجوزهای نقش پایین را به ارث می‌برد
Separation of dutiesقید ترکیب‌نشدن نقش‌های متضاد (SSD هنگام اعطا، DSD در هر نشست)
Role explosionنقش‌های بسیار زیاد از ترکیب ویژگی‌ها
ABACکنترل دسترسی مبتنی بر ویژگی (NIST SP 800-162)
ویژگی (Attribute)نام و مقدار روی subject، resource، action یا environment
سیاست (Policy)قاعده‌ای که تحت شرط‌ها permit یا forbid می‌کند
OPAOpen Policy Agent، موتور سیاست عمومی
Regoزبان سیاست OPA
Cedarزبان سیاست با خاستگاه AWS با permit و forbid
ReBACکنترل دسترسی مبتنی بر رابطه
Zanzibarسیستم مجوزدهی جهانی گوگل (USENIX ATC 2019)
Relation tupleحقیقت object#relation@subject
Usersetسوژه‌ای که خودش object#relation است
Rewrite ruleتعریف یک relation از relationهای دیگر (this، computed_userset، tuple_to_userset)
CheckAPI: آیا سوژه روی شیء relation دارد
ExpandAPI: userset مؤثر یک relation روی شیء
List objectsپرسش معکوس: شیءهایی که سوژه به آن‌ها می‌رسد
Zookieتوکن سازگاری مات (Zanzibar)؛ SpiceDB آن را ZedToken می‌نامد، snapshot token
OpenFGAسرور مجوزدهی به سبک Zanzibar در CNCF
SpiceDBدیتابیس الهام‌گرفته از Zanzibar از AuthZed
Ketoسرور مجوز متن‌باز Ory
Permifyسرویس مجوزدهی الهام‌گرفته از Zanzibar
Capabilityارجاع جعل‌ناپذیر که اختیار می‌دهد
Macaroonاعتبارنامهٔ bearer با caveatهای زنجیره‌ای زمینه‌ای
Multi-tenancyچندین مشتری روی یک سیستم
Tenant idستون و کلیدی که مشتری را مشخص می‌کند
Row-level securityسیاست‌های هر ردیف در PostgreSQL که دیتابیس اعمال می‌کند
Scope vs permissionscope تفویض client است؛ permission حق کاربر
Policy as codeسیاست در کنترل نسخه با تست و CI
Policy testingماتریس‌های خودکار permit و deny برای سیاست
Decision cachingاستفادهٔ دوباره از تصمیم‌های اخیر؛ TTL پنجرهٔ لغو است
Reverse indexindex از کاربر به شیءها برای فهرست‌کردن
Audit logسابقهٔ تصمیم‌ها و تغییر grantها
Explainabilityتوانایی گفتن چرا تصمیم گرفته شد
Zero Trustهیچ اعتماد ضمنی از موقعیت شبکه؛ هر درخواست تأیید می‌شود
NIST SP 800-207نشریهٔ Zero Trust Architecture
BeyondCorpمدل دسترسی zero trust گوگل
ZTNAZero Trust Network Access، دسترسی به برنامه‌ها از طریق gateway
Device postureوضعیت سلامت و مدیریت دستگاه client
Continuous verificationارزیابی دوبارهٔ اعتماد در طول نشست
Least privilegeفقط دسترسی لازم برای کار
Gateنقطهٔ ورود مجوزدهی ability در Laravel
Policy (Laravel)کلاس با متدهای مجوز برای هر مدل
authorizeGate::authorize: روی رد exception می‌دهد
can middlewarealias route که پیش از controller مجوز می‌دهد
Gate::beforeقلابی که پیش از هر چک اجرا می‌شود؛ نتیجهٔ غیر null نهایی است
spatie/laravel-permissionبستهٔ ذخیرهٔ نقش و مجوز برای Laravel

منابع ​

ساخته‌شده توسط Morteza Negahi