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; August 2020)
Summary: Authorization answers "may this authenticated subject do this action on this resource right now?". The models differ in what they look at: an access control list (ACL) looks at one object, RBAC at the subject's job, ABAC at attributes of subject, resource, action and environment, ReBAC at the graph of relationships between subjects and objects. Zero Trust says the answer must be computed per request and never inferred from the network. Focus: authentication vs authorization, the XACML roles (PEP, PDP, PIP, PAP), ACLs, NIST RBAC (roles, hierarchies, separation of duties, role explosion), ABAC (NIST SP 800-162, XACML, ALFA, OPA Rego, Cedar), ReBAC (Google Zanzibar, relation tuples, usersets, rewrite rules, check, expand, list objects, zookies, OpenFGA, SpiceDB, Ory Keto, Permify), capabilities and macaroons, multi-tenancy isolation and row-level security, OAuth scopes vs permissions, policy as code and policy testing, decision caching and the reverse-index problem, audit log and explainability, Zero Trust (NIST SP 800-207, BeyondCorp, ZTNA, device posture, continuous verification), and Laravel 13 Gates, Policies and spatie/laravel-permission next to Go middleware with OPA, Cedar and OpenFGA. Learning goal: For a given product, pick RBAC, ABAC, ReBAC or a layered mix, place the enforcement and decision points, keep tenants apart, make revocation and listing work at scale, test and audit the policies, and implement the check in Laravel 13 and Go with tests.
This chapter sits in the Security group, after Authentication (who the caller is), JWT Deep Dive (a token that carries claims) and OAuth 2.0, OpenID Connect & SSO (delegated access and scopes), and before Cryptography in Practice, OWASP Top 10 (broken access control is the first item there) and Mutual TLS & Securing Service-to-Service Traffic (the workload identity that Zero Trust needs between services). The threat model is in Security Foundations; the database mechanics of roles and row-level security are in Database Security and Multi-Tenancy Strategies. This page owns the system-level decision: which model, where the check runs, how fast it must be, how it is tested and how it fails.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why authorization is its own problem | Why it exists |
| Ferraiolo and Kuhn, NIST ABAC, Zanzibar, BeyondCorp | Where it comes from |
| Authentication vs authorization | Authn vs authz |
| PEP, PDP, PIP, PAP | The XACML roles |
| Access control lists | ACLs |
| Roles and permissions | RBAC |
| Hierarchies, separation of duties, role explosion | Hierarchies and constraints |
| Attributes and policies | ABAC |
| XACML, ALFA, Rego, Cedar | Policy languages |
| Tuples, usersets, rewrite rules | ReBAC and Zanzibar |
| Zookies and the new enemy problem | Consistency |
| OpenFGA, SpiceDB, Keto, Permify | ReBAC products |
| Capabilities and macaroons | Capabilities |
| Tenant id in every query, row-level security | Multi-tenancy |
| OAuth scopes vs user permissions | Scopes vs permissions |
| Policy as code, policy testing | Policy as code |
| Decision caching, batch checks, listing | Performance |
| Audit log and explainability | Audit |
| NIST SP 800-207 tenets | Zero Trust |
| BeyondCorp, ZTNA, device posture, mTLS | Zero Trust in practice |
| Exact knobs and error codes | Mechanics |
| Code | Go, Laravel, SQL |
| Classic failures and fixes | Solving the classic problems |
| Which model for which product | Choosing |
| Monolith to distributed system | In architecture |
| Numbers from the lab | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Authentication and authorization are different questions.
| Question | Name | Typical mechanism | Failure status | Failure meaning |
|---|---|---|---|---|
| Who are you? | Authentication (authn) | Password, MFA, session cookie, JWT, mTLS certificate | 401 Unauthorized | I do not know who you are |
| What may you do? | Authorization (authz) | Roles, attributes, relationships, policies | 403 Forbidden (or 404) | I know you; the answer is no |
| Which app may act for you? | Delegation | OAuth 2.0 scopes, consent | 403 insufficient_scope | The client was not granted that |
The four models in one row each.
| Model | Decision looks at | Typical question | Strength | Weakness | Products |
|---|---|---|---|---|---|
| ACL | One object and its list of subjects | Is Ana on the list of this file? | Simple, per object | Does not scale with objects; no inheritance | POSIX permissions, S3 ACLs, NTFS |
| RBAC | The subject's roles | Does Ana hold a role with invoice:approve? | Easy to audit, maps to job functions | Role explosion; blind to the object and context | spatie/laravel-permission, Keycloak roles, AWS IAM groups |
| ABAC | Attributes of subject, resource, action, environment | Same department, business hours, managed device? | Fine-grained, central policy | Hard to answer "who can see X?" and to debug | OPA, Cedar, XACML, AWS IAM conditions |
| ReBAC | Paths in a graph of relations | Is Ana an editor of the folder that contains this doc? | Sharing, inheritance, nesting | Needs a store, consistency and a reverse index | Zanzibar, OpenFGA, SpiceDB, Ory Keto, Permify |
The XACML roles (also used by NIST SP 800-162 and SP 800-207).
| Role | Short | Job | Where it lives in practice |
|---|---|---|---|
| Policy Enforcement Point | PEP | Intercepts the request, asks, enforces the answer | API gateway, middleware, Laravel Gate and can middleware, Envoy filter |
| Policy Decision Point | PDP | Evaluates policies against attributes, returns permit or deny | OPA, Cedar, SpiceDB, OpenFGA, a Laravel Policy class |
| Policy Information Point | PIP | Supplies attributes and relationships the PDP lacks | User service, HR database, device inventory, tuple store |
| Policy Administration Point | PAP | Where policies are authored, versioned and published | Git repository plus a CI pipeline, an admin console |
Zero Trust in one table.
| Old assumption | Zero Trust rule | What you build |
|---|---|---|
| Inside the network means trusted | Network location alone does not imply trust | A PEP in front of every resource, mTLS between services |
| Log in once, roam freely | Access is granted per session and re-evaluated | Short sessions, step-up, continuous verification |
| Identity is enough | Device posture and context count too | Device inventory, posture checks, risk signals |
| Broad roles are fine | Least privilege per request | Narrow permissions, just-in-time grants |
Why it exists
Every endpoint of a real system makes a decision: may this caller read invoice 4711? A system without a deliberate model answers with scattered if statements, one per controller. The statements drift, a new endpoint forgets one, and the result is the number one entry of the OWASP Top 10: broken access control. OWASP's Authorization Cheat Sheet states the baseline in two rules: "Enforce Least Privileges" and "Deny by Default" ("The application must always make a decision, whether implicitly or explicitly, to either deny or permit the requested access").
| Simple side | Rich side | The trade you make |
|---|---|---|
A boolean is_admin column | A policy engine with its own language | Auditability and finer grain against operational weight |
| Check in the controller | Check in a central PDP | One place to reason against a network hop and a new dependency |
| Roles on the user | Relationships on the object | Easy "what can Ana do" against easy "who can open this doc" |
| Static grants | Dynamic attribute rules | Predictable review against flexibility (and surprise) |
| Deny on doubt | Allow on doubt | Safety against availability when the PDP is down |
Everyday picture. A building has a badge reader at every door. RBAC is the colour of your badge (staff, cleaner, visitor). ABAC adds rules read from context: only in working hours, only if you are escorted. ReBAC is "the person who booked this meeting room may let in guests, and the guests may use the whiteboard in it". Zero Trust removes the guard at the front gate who waved everyone through: every door re-checks, every time.
Three common misunderstandings, up front
- "We have login, so we have authorization." A valid session proves identity only. The most common real breach is a logged-in user changing an id in the URL (insecure direct object reference, broken object level authorization).
- "RBAC is old, ABAC and ReBAC replace it." They layer. Almost every product keeps a coarse role check (may this person use the billing module at all), then an object-level rule (may they open this invoice).
- "Zero Trust is a product you buy." NIST SP 800-207 calls it "a collection of concepts and ideas"; a ZTA is "an enterprise's cybersecurity plan". Products (ZTNA gateways, identity-aware proxies) implement parts of it.
Where it comes from
| Year | Event | Source |
|---|---|---|
| 1992 | Role-based access control formalized by David Ferraiolo and Rick Kuhn | NIST RBAC project page |
| 2004 | The NIST RBAC model adopted as ANSI/INCITS 359-2004 (11 February 2004); revised as INCITS 359-2012 | NIST RBAC project page |
| 2014 | NIST SP 800-162 defines ABAC (January 2014; updates as of 2 August 2019) | NIST SP 800-162 |
| 2014 | BeyondCorp: "A New Approach to Enterprise Security" (Ward and Beyer, ;login: Vol. 39 No. 6); macaroons (NDSS 2014) | research.google |
| 2016 | BeyondCorp: "Design to Deployment at Google" (;login: 41), dynamic tiers of trust for devices | research.google |
| 2019 | Zanzibar: Google's Consistent, Global Authorization System (USENIX ATC 2019) | research.google |
| 2020 | NIST SP 800-207 Zero Trust Architecture (August 2020) | NIST SP 800-207 |
What the primary sources actually say:
- NIST's RBAC page says RBAC "has become the predominant model for advanced access control because it reduces this cost" (the cost of security administration in large networks).
- NIST SP 800-162 defines ABAC as "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". It also names the cost of pure RBAC: ad hoc roles "leading to what is often termed 'role explosion'".
- The Zanzibar paper reports "trillions of access control lists and millions of authorization requests per second", with "95th-percentile latency of less than 10 milliseconds and availability of greater than 99.999% over 3 years of production use".
- The BeyondCorp abstract: perimeter security is "problematic because, when that perimeter is breached, an attacker has relatively easy access to a company's privileged intranet".
- Open-source successors of Zanzibar: SpiceDB (AuthZed) says the paper inspired it; Ory Keto calls itself "the first open-source implementation" of the Zanzibar design; Permify says it is "inspired by Google's consistent, global authorization system"; OpenFGA is the CNCF project with a Zanzibar-style model language.
The concept catalogue
Each block follows the same order: plain words, the usual wrong belief, a definition, a timeline, real scenarios, how products provide it, and the fix.
Authentication vs authorization Must-know
In plain words: authentication is showing an ID at the door; authorization is the list that says which rooms that ID opens.
Common misunderstanding: "If the JWT is valid the request is allowed." A valid signature proves who issued the claims and that they were not altered. Whether this subject may touch this object is a separate decision, and claims such as role: admin inside a token are only as fresh as the token (see JWT Deep Dive).
Definition: authentication establishes the subject (user or workload) and produces an identity with attributes; authorization is the function decide(subject, action, resource, context) returning permit or deny, evaluated after authentication and before the action.
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)Real scenarios: a mobile app user changes invoices/4711 to invoices/4712 (needs an object check, not a login check); a support agent may read any ticket but may not export them (permission, not identity); a service account of the billing service may read invoices but not users (workload authorization); an OAuth client may only read profile because the user granted only that scope.
| Situation | HTTP status | Why |
|---|---|---|
| No or bad credentials | 401 | Authentication failed; send WWW-Authenticate |
| Known user, not allowed | 403 | Authorization failed |
| Known user, resource must not be revealed | 404 | Hides existence (Laravel Response::denyAsNotFound()) |
| Policy service unreachable | 503 (fail closed) | Never turn an error into an allow |
Fix / how to use it: keep the two steps in two layers (authentication middleware, then authorization middleware or policy); never read permissions from client-supplied data. Code is in Go and Laravel.
The XACML roles: PEP, PDP, PIP, PAP Must-know
In plain words: one part asks, one part decides, one part supplies facts, one part holds the rulebook.
Common misunderstanding: "The policy engine blocks requests." The PDP only answers. The PEP blocks. If the PEP forgets to call it, or ignores an error, nothing is protected.
Definition: the roles come from the XACML reference architecture, which NIST SP 800-162 summarizes as "Policy Decision Points (PDPs), Policy Enforcement Points (PEPs), Policy Administration Points (PAPs), and Policy Information Points (PIPs)". NIST SP 800-207 reuses the idea: the policy engine (PE) and policy administrator (PA) together form the PDP, and the PEP sits in front of the resource.
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; logReal scenarios: Envoy ext_authz calls OPA (the sidecar is the PEP); an API gateway such as Kong or NGINX calls an auth service; a Laravel can:update,document middleware is the PEP and the DocumentPolicy class is the PDP; a database with row-level security is a PEP and PDP in one.
| Placement | PEP | PDP | Latency | Notes |
|---|---|---|---|---|
| Embedded library | Your code | In-process (Cedar library, Laravel Policy, a Go evaluator) | Microseconds | Policy ships with the binary |
| Sidecar | App or Envoy | OPA on localhost | Sub-millisecond to a few ms | Bundles pushed by the PAP |
| Central service | App | SpiceDB, OpenFGA, an auth service | A network round trip | One source of truth for relationships |
| Gateway | Gateway | Gateway plugin or OPA | Per request, at the edge | Coarse checks only; the service still checks objects |
Fix / how to use it: define one Request and one Decision type (see authz.go) so the PDP can change without touching handlers; make the PEP fail closed.
Access control lists (ACLs) Important
In plain words: every object carries its own list of who may do what to it.
Common misunderstanding: "ACLs are legacy." Document sharing ("anyone with the link", "Ana can edit") is an ACL; Zanzibar's name is literally an ACL system. What changed is how ACLs are stored and inherited.
Definition: an ACL is a list of (subject, permission) entries attached to an object. Checking is cheap for one object; the question "what can Ana access" needs a scan of every object, which is the reverse-index problem again.
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 -> denyReal scenarios: Linux file mode bits and POSIX ACLs; S3 bucket and object ACLs; Windows NTFS DACLs; Redis ACL (ACL SETUSER) for commands and keys; a shared_with table on a document.
| System | ACL granularity | Inheritance |
|---|---|---|
| POSIX filesystem | owner, group, other, plus extended ACL entries | Default ACLs on directories |
| Amazon S3 | per bucket and per object | None across objects; bucket policy is preferred |
| Redis 6+ ACL | per user: commands, key patterns, channels | None |
| Google Drive style sharing | per file and folder | Folder to children (this is ReBAC) |
Fix / how to use it: a table shared_with(resource_id, subject, permission) is a legitimate start; when you add groups and folders, you are building ReBAC and should model it as tuples (see SQL).
RBAC: users, roles, permissions, sessions Must-know
In plain words: you give people a job title (role), the title carries the permissions, so you manage titles instead of people.
Common misunderstanding: "A role is a permission." A permission is one action on one kind of object (invoice:approve). A role is a bag of permissions that matches a job. Checking hasRole('admin') in application code couples the code to org charts; check permissions and let roles group them (the spatie/laravel-permission documentation says the same).
Definition (NIST RBAC): the reference model has users, roles, permissions (an operation on an object), user assignment (UA), permission assignment (PA), sessions (a user activates a subset of assigned roles), and optionally a role hierarchy and constraints. It became ANSI/INCITS 359-2004. A user can do something when an active role holds the permission.
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 -> denyReal scenarios: a back-office app with admin, support and finance; Kubernetes Role and RoleBinding; AWS IAM groups and roles; Keycloak realm and client roles; a Laravel app using spatie/laravel-permission.
| Product | What "role" is | Permission format | Notes |
|---|---|---|---|
| spatie/laravel-permission | Row in roles, linked to permissions | Free string (edit articles) | Registers permissions with the Laravel Gate; v7/v8 list Laravel 12 and 13 |
| Kubernetes RBAC | Role or ClusterRole of rules | verb on resource | Additive only; no deny |
| AWS IAM | Role assumed by a principal | Action strings in policies | Policies also allow conditions (ABAC) and explicit deny |
| Keycloak | Realm role, client role, composite role | Role names | Composite roles are a hierarchy |
Fix / how to use it: store roles and permissions in tables (see SQL), check permissions in code, grant through roles, and keep the number of roles small (next block). Code: Laravel and the pure evaluator in Go.
Role hierarchies, separation of duties, role explosion Must-know
In plain words: a senior role inherits what a junior role can do; some role pairs must never meet in one person; and if you keep inventing roles for every case you end up with more roles than people.
Common misunderstanding: "More roles means finer control." Past a point it means no one can audit the system. A combination such as department x region x level (6 x 4 x 3) already creates 72 roles; NIST SP 800-162 names the result "role explosion".
Definition: a role hierarchy is a partial order where senior roles inherit junior permissions. Static separation of duties (SSD) forbids a user from being assigned conflicting roles at all (for example clerk and approver). Dynamic separation of duties (DSD) allows both assignments but forbids activating both in one session. Both constraints are "no user (session) may hold N or more of this role set".
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} okReal scenarios: four-eyes principle for payments (creator cannot approve), a trader who may not also be a risk officer, a bank teller who may be an auditor on another day, a hierarchy admin > manager > employee, a time-boxed break-glass role granted for two hours (expires_at).
| Technique | Fights role explosion how | Cost |
|---|---|---|
| Role hierarchy | Senior roles inherit; fewer role definitions | Cycles must be rejected; audits need the closure |
| Permission-based checks | Code never names roles | Needs a permission catalogue |
Parameterized roles (role plus scope, for example approver@region=EU) | One role, many scopes | Moves toward ABAC |
| Add attributes (ABAC layer) | Replaces a role per attribute combination | Policy review becomes essential |
| Add relationships (ReBAC layer) | Replaces a role per project or document | Needs a relationship store |
Fix / how to use it: the in-process model in Go (rbac package) shows hierarchy closure, SSD at assignment and DSD at session start, with tests.
ABAC: attributes and policies Must-know
In plain words: instead of "Ana is a manager", the rule says "allow if the user's department equals the document's department, it is a weekday, and the device is managed".
Common misunderstanding: "ABAC means no roles." A role is just one attribute of the subject. ABAC generalizes RBAC, and NIST SP 800-162 notes that ABAC "avoids the need for capabilities (operation/object pairs) to be directly assigned to subject requesters or to their roles or groups".
Definition (NIST SP 800-162): access is decided by evaluating attributes of the subject, the object (resource), the requested operation (action), and in some cases the environment, against policy. Attributes are name and value pairs. Policies are rules over attributes. Environment attributes include time, location, threat level and device state.
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)Real scenarios: "contractors may read only non-confidential documents from managed devices"; "doctors may read records of patients on their ward"; "payments above 10,000 need an approver with a higher limit"; AWS IAM Condition blocks and tag-based access (aws:PrincipalTag equals aws:ResourceTag); Kubernetes admission policies.
| Aspect | RBAC | ABAC |
|---|---|---|
| Where truth lives | User-role and role-permission tables | Attributes in many systems, plus policies |
| "What can Ana do?" | Easy: union of roles | Hard: evaluate every resource |
| "Who can read this?" | Easy: roles holding the permission | Hard: evaluate every subject |
| Change a rule | Edit a role | Edit a policy and re-test everything it touches |
| Typical failure | Role explosion | Wrong or stale attribute, surprising interaction between rules |
Fix / how to use it: keep attribute sources (PIPs) few and fast, version policies in Git, combine with deny-overrides and default deny; the abac package in Go does that in 50 lines, and the Laravel DocumentPolicy in Laravel is ABAC in PHP.
Policy languages: XACML, ALFA, Rego, Cedar Important
In plain words: a policy language lets you write the rules as data or code that a PDP can evaluate, instead of if statements spread over controllers.
Common misunderstanding: "A policy language is a security feature." It is a way to make rules reviewable, testable and analyzable. A badly written policy is just as wrong in Rego as in PHP.
Definition: XACML is an OASIS XML standard with the PEP/PDP/PIP/PAP architecture, targets, rules and combining algorithms; ALFA (Abbreviated Language for Authorization) is a compact syntax that compiles to XACML. OPA (Open Policy Agent) is a general policy engine whose language is Rego; the OPA docs say it "accepts arbitrary structured data as input" and is "domain-agnostic". Cedar is a language from AWS: policies have an effect (permit or forbid), a scope (principal, action, resource) and optional conditions, and the combination rule is: allow when at least one permit matches and no forbid matches, otherwise deny.
| Language | Style | Default | Conflict rule | Analyzable | Where used |
|---|---|---|---|---|---|
| XACML 3.0 | XML, targets and rules | Not applicable | Combining algorithms (deny-overrides, permit-overrides, first-applicable) | Limited | Enterprise IAM suites |
| ALFA | Compact text over XACML | Same as XACML | Same | Limited | Axiomatics tooling |
| Rego (OPA) | Datalog-like rules over JSON | undefined unless default allow := false | You write it (deny sets, count(deny) == 0) | By tests | Kubernetes Gatekeeper, Envoy, Terraform checks, APIs |
| Cedar | Declarative permit and forbid | Deny | forbid overrides permit | Schema validation, formal analysis | Amazon Verified Permissions, cedar-go |
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
}// 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 }; 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)Fix / how to use it: pick one language per layer, write the default as deny, make the conflict rule explicit (forbid wins), and test (see policy as code). OPA's REST Data API returns HTTP 200 with no result property when the queried rule is undefined, so the client must treat a missing result as deny, as the Go httpguard.OPA decider does.
ReBAC and Zanzibar: relation tuples, usersets, rewrite rules Must-know
In plain words: permission follows relationships: you may open a document if you are in a group that is a viewer of the folder that contains it.
Common misunderstanding: "ReBAC is a graph database feature." The model is a graph, but Zanzibar stores flat relation tuples in a normal database (Spanner at Google) and computes answers by walking them under rewrite rules.
Definition (Zanzibar paper): a relation tuple has the text form object#relation@user, where the subject is a user id or a userset object#relation. Table 1 of the paper lists: doc:readme#owner@10 (user 10 owns the doc), group:eng#member@11, doc:readme#viewer@group:eng#member (members of group eng are viewers), doc:readme#parent@folder:A#... (the doc is in folder A). A namespace configuration defines for each relation a userset rewrite rule: this (direct tuples), computed_userset (another relation on the same object), tuple_to_userset (follow a tuple, such as parent, to another object and use a relation there), combined with union, intersection or exclusion. The APIs are Check, Read, Write, Watch and Expand; Expand returns the effective userset tree, and Leopard is the indexing system that speeds up deeply nested sets.
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: allowedReal scenarios: Google Drive and Docs sharing (the paper's own example), GitHub-style organization, repository and team permissions, Notion-style page trees, "project members may see tickets of the project" in SaaS. The paper names Calendar, Cloud, Drive, Maps, Photos and YouTube as Zanzibar clients.
| Rewrite operator | Meaning | Example |
|---|---|---|
this | Subjects written directly as tuples | doc#viewer@user:bob |
computed_userset | Same object, other relation | owner implies editor implies viewer |
tuple_to_userset | Follow a tuple to another object | viewers of the parent folder |
| union | Any child grants | this or editor or parent viewer |
| intersection | All children must grant | member and device_trusted |
exclusion (but not) | Base minus subtract | viewer but not blocked |
// 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
}Fix / how to use it: model objects, relations and parents first, not roles; write a small configuration like the one in the tests (paperConfig), then buy or run a Zanzibar-style service when you need scale, consistency and a reverse index. The tests are in rebac_test.go.
Consistency in ReBAC: zookies and the new enemy problem Must-know
In plain words: if you remove someone from a folder and then put a secret in it, the removal must be visible to the check that guards the secret, even if some replica is a bit behind.
Common misunderstanding: "Eventual consistency is fine for permissions." For content access, a stale answer can leak. The paper calls this the "new enemy" problem: it "can arise when we fail to respect the ordering between ACL updates or when we apply old ACLs to new content".
Definition: Zanzibar issues an opaque token, a zookie, that encodes "a current global timestamp". The client stores the zookie with the content version it protects and sends it back on later checks, so the check is evaluated at a snapshot at least as fresh as that version. Google stores ACLs in Spanner so TrueTime gives each write a timestamp; the paper's two properties are external consistency and snapshot reads with bounded staleness. SpiceDB calls its token a ZedToken and exposes consistency levels: minimize_latency (default for most APIs), at_least_as_fresh, at_exact_snapshot, fully_consistent (default for writes). OpenFGA exposes MINIMIZE_LATENCY (default) and HIGHER_CONSISTENCY on Check, Expand, ListObjects and ListUsers; it warns that after a write a MINIMIZE_LATENCY check may be served from cache and miss the change.
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 -> DENYReal scenarios: share-then-upload flows; removing a departing employee from a group at 17:00 and a manager adding files at 17:01; a permission change followed by an immediate "refresh" of the page (read-your-writes); bulk exports that must see the latest revokes.
| System | Token | Levels | Default |
|---|---|---|---|
| Zanzibar | zookie (timestamp) | Snapshot at or after zookie; "at least as fresh" | Evaluate at an old enough snapshot for speed |
| SpiceDB | ZedToken | minimize_latency, at_least_as_fresh, at_exact_snapshot, fully_consistent | minimize_latency, except writes and schema |
| OpenFGA | none (consistency enum) | MINIMIZE_LATENCY, HIGHER_CONSISTENCY | MINIMIZE_LATENCY |
| Ory Keto | snapshot token (Zanzibar design) | See Keto docs | Not verified here |
| Permify | snapshot token (Zanzibar design) | See Permify docs | Not verified here |
Fix / how to use it: store the token next to every protected object version, send it on every check of that object, and use the strongest level only for the few paths where staleness leaks (share dialogs, deletes). The rebac.Store in Go models revisions; its test TestSnapshotAvoidsNewEnemy reproduces the table above.
ReBAC products: OpenFGA, SpiceDB, Ory Keto, Permify Important
In plain words: you do not have to build Zanzibar; several open-source servers implement the idea, each with its own model language.
Common misunderstanding: "They are interchangeable." Model languages, consistency tokens, deployment and listing performance differ. Switching later means rewriting the model and re-importing tuples.
Definition: all four store relation tuples, evaluate Check against a schema or model, and expose list APIs. OpenFGA uses a DSL with define viewer: [user] or editor or viewer from parent; SpiceDB uses a schema language with relation and permission definitions and the arrow operator parent->viewer; Ory Keto (the open-source core of Ory Permissions) and Permify state that they follow the Zanzibar paper.
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 blockeddefinition 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
} 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 WriteRelationshipsReal scenarios: a B2B SaaS where users belong to organizations, organizations own projects, projects own documents; a code host with organizations, teams and repositories; a document editor with folder inheritance and link sharing (user:* for "everyone").
| Product | Model language | Consistency | List objects | Notes |
|---|---|---|---|---|
| OpenFGA | DSL (define, or, and, but not, from) | MINIMIZE_LATENCY default, HIGHER_CONSISTENCY | ListObjects, streamed variant; cost varies with model, tuple count, and and / but not being more expensive than or | Contextual tuples let a request carry tuples that are not stored |
| SpiceDB (AuthZed) | definition, relation, permission, arrow -> | ZedTokens and four levels | LookupResources, LookupSubjects | Paper-inspired; fully_consistent for writes |
| Ory Keto | Relation tuples and namespaces (Zanzibar design) | See docs | See docs | Open source core of Ory Permissions |
| Permify | Schema language (Zanzibar-inspired) | See docs | See docs | Described as inspired by Zanzibar |
Fix / how to use it: pin the authorization model id in the client (the Go SDK has AuthorizationModelId in ClientConfiguration), write models in version control, load them in CI, and use HIGHER_CONSISTENCY or a ZedToken only on paths where staleness leaks. The compile-checked adapter is in Go (fga package).
Capabilities and macaroons Good to know
In plain words: a capability is an unforgeable key to one thing; whoever holds the key can use it, so there is no list to look up.
Common misunderstanding: "A capability is just a bearer token." A bearer token is a capability in practice, which is exactly why it must be scoped and short-lived. The research question is how to let the holder narrow it before passing it on.
Definition: in capability-based security, authority travels with an unforgeable reference (a file descriptor, a pre-signed URL, a signed link). Macaroons (Birgisson et al., NDSS 2014) are bearer credentials with "contextual caveats": the holder can add caveats (for example "expires in 5 minutes", "read only") using chained HMACs without contacting the issuer, and the verifier checks all caveats. JWTs are the more common signed-token form and carry claims instead of caveats (see JWT Deep Dive).
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 denyReal scenarios: S3 and GCS pre-signed URLs; a share link that grants read access to one file; Unix file descriptors passed over a socket; delegating a sub-task to another service with a narrower token.
| Mechanism | Revocable before expiry | Delegable and attenuable | Typical use |
|---|---|---|---|
| Pre-signed URL | Only by rotating the key | No | Temporary file access |
| JWT access token | With a deny list or short lifetime | Re-minting needed | API access |
| Macaroon | By caveat on a revocation id | Yes, by the holder | Decentralized delegation |
| ReBAC tuple | Yes, delete the tuple | Yes, write a tuple | Sharing inside a product |
Fix / how to use it: prefer short lifetimes and narrow scope for any bearer credential; use a ReBAC tuple when you need revocation and listing.
Multi-tenancy isolation Must-know
In plain words: in a SaaS product many customers share the same tables; every query must be filtered to the customer's rows, and a forgotten filter is a data breach.
Common misunderstanding: "The role check protects tenants." A role such as admin is per tenant. A global admin check without the tenant id lets an admin of tenant A read tenant B's invoice by id.
Definition: carry the tenant id (tenant_id) in every row, every key and every authorization request; enforce it in three places: the policy (forbid when subject tenant differs from resource tenant), the query layer (Laravel global scope, repository filter), and the database (PostgreSQL row-level security with FORCE ROW LEVEL SECURITY, because the table owner is otherwise exempt). Answer cross-tenant access with 404, not 403, so ids do not leak existence. Isolation models (shared schema, schema per tenant, database per tenant) are in Multi-Tenancy Strategies; row-level security mechanics and roles are in Database Security.
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 enumerationReal scenarios: GET /invoices/4711 with an id of another tenant; a background job with no request context that forgets SET app.tenant_id; a cache key user:42:profile shared between tenants; an analytics query that joins tables without the tenant column.
| Technique | Where | Protects against | Gap |
|---|---|---|---|
| Policy forbid on tenant mismatch | PDP | API-level IDOR across tenants | Not applied to raw SQL |
Laravel global scope (addGlobalScope) | ORM | Forgotten where in Eloquent queries | DB::table() and raw queries bypass it |
PostgreSQL RLS with set_config('app.tenant_id', ..., true) | Database | Everything that reaches the table | Table owner and superuser bypass unless FORCE; pool leaks if set per session |
| Schema or database per tenant | Infrastructure | Blast radius | Operational cost |
Fix / how to use it: the Document model, SetTenant middleware and schema.sql in Laravel and SQL do all three layers; the Go httpguard.Enforce checks tenant before the PDP and answers 404.
Scopes vs permissions Must-know
In plain words: an OAuth scope is what the user allowed an app to do on their behalf; a permission is what the user is allowed to do at all. The effective right is the intersection.
Common misunderstanding: "scope vs permission is the same thing, so the token's scope list is my authorization." A token with scope invoices:write for a user who has no write permission must still be denied, and a user with permission whose token has only profile must also be denied. RFC 6749 section 3.3 defines the scope as "the scope of the access request", a list of space-delimited, case-sensitive strings "defined by the authorization server"; it carries delegation by the resource owner, not the user's rights.
Definition: effective access = (rights of the user, from RBAC/ABAC/ReBAC) AND (scopes granted to this client by this user). Client-credentials tokens have no user: their permissions are those of the service identity, usually expressed as scopes or roles in the token. Details of scopes, consent and tokens are in OAuth 2.0, OpenID Connect & SSO.
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)| Aspect | Scope | Permission |
|---|---|---|
| Granted by | The resource owner at consent | An administrator or the system |
| Granted to | A client application acting for the user | A user or service identity |
| Lives in | The access token (or introspection result) | The authorization system |
| Checked by | Token validation at the API | The PDP |
| Revocation | Revoke the grant or token | Change roles, attributes, tuples |
Fix / how to use it: validate scope at the edge, then call the PDP with the user as subject; never grant a user permission just because a token carries a scope.
Policy as code and policy testing Important
In plain words: policies are written in files, reviewed in pull requests, tested by machines and deployed like software.
Common misunderstanding: "Tests on the application cover the policy." Application tests usually test the happy path. Policy tests state the matrix: for each role or attribute set, which actions are permitted and which are denied, including the cases that must never be allowed.
Definition: policy as code means policies live in version control, have tests, pass static checks (OPA opa check, Cedar validation against a schema), roll out through the PAP (OPA bundles, Cedar policy stores) and write decision logs. OPA has a built-in test runner (opa test); Cedar validates policies against a schema.
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| Test type | What it proves | Tool |
|---|---|---|
| Table test per role or attribute set | The permit and deny matrix | opa test, Go table tests, PHPUnit |
| Negative tests | Things that must never be allowed (cross-tenant) | Same |
| Property or invariant tests | "No decision depends on a field that is client-supplied" | Fuzz tests |
| Schema validation | Policies reference real attributes | Cedar validator |
| Shadow mode | New policy evaluated beside the old, differences logged | Decision logs |
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"}})Fix / how to use it: the Rego policy above passed opa test (3 of 3) with OPA 1.22.4 in this chapter's QA; the Go tests in Go cover the other engines; run both in CI.
Performance: decision caching, batch checks and the listing problem Must-know
In plain words: authorization runs on every request, so it must be fast; the hard part is not "may Ana open this" but "which of 10,000 documents may Ana see".
Common misunderstanding: "Filter the list in the application after loading it." That loads everything, breaks pagination and leaks counts. Listing is a reverse-index problem: you need to find objects from a subject, not subjects from an object.
Definition: a point check walks the graph from one object. A list query ("list objects") must start from the subject and walk relationships backwards, or precompute them. Zanzibar's answer is Leopard, a specialized index for nested sets. Databases answer by joining the permission tables inside the query. Products offer ListObjects (OpenFGA), LookupResources (SpiceDB). Caching decisions trades staleness for latency: the TTL is the revocation window.
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| Technique | Latency | Staleness | Complexity | Use when |
|---|---|---|---|---|
| Decision cache with TTL (positive 30 s, negative 5 s) | Microseconds on a hit | Up to the TTL after a revoke | Low | Hot objects, read-heavy |
| Versioned cache key (bump a tenant version on write) | Microseconds | Near zero | Medium | Few writes |
| Batch check | One round trip | Same as PDP | Low | Page of results |
| Denormalised permission set | One read | Until rebuilt | High | Search results filtering |
Reverse index (relation_tuples_by_subject) | One indexed query | Same as the table | Medium | "What can I see" lists |
| Pushdown to the datastore (partial evaluation, row-level security) | One query | None | High | Large lists with simple rules |
Fix / how to use it: cache only definite answers with short TTLs, never cache errors, separate positive from negative TTLs, key by tenant, subject, action and resource, and bump a version on writes (the httpguard.Cache in Go and RelationshipChecker in Laravel). For lists use a reverse index or ListObjects, not N checks.
Audit log and explainability Important
In plain words: when someone asks "why could Bob read that file?" or "why was Ana refused?", you must be able to answer from a record, not from guesswork.
Common misunderstanding: "An access log is an audit log." An access log says a request happened. An authorization audit record says which decision was made, by which policy, from which attributes and at which policy version.
Definition: an audit log record has who (subject), what (action and resource), when, the decision, the reason or policy ids, the attribute and policy versions and a request id. OPA writes decision logs with a decision_id (returned by the REST API when decision logging is on); Cedar returns diagnostics listing the determining policy ids; OpenFGA Check can be complemented by Expand to show why; Laravel Gate::inspect() returns a Response with a message and status.
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)| Need | Mechanism | Product |
|---|---|---|
| Why was this allowed or denied | Decision reason, policy ids | Cedar diagnostics, Laravel Response::message(), authz.Decision.Reason and Policies |
| Who can access this object | Expand or ListUsers | OpenFGA, SpiceDB LookupSubjects, Zanzibar Expand |
| What can this subject access | ListObjects or LookupResources | OpenFGA, SpiceDB |
| Tamper-evident history | Append-only store, shipped off-host | SIEM, WORM storage |
| Access reviews | Periodic export of grants | Role and tuple tables |
Fix / how to use it: log every deny and every change to grants; treat grant changes (role assigned, tuple written) as security events; never log secrets or full token values. The Go AuditFunc and the Laravel authz.decision log line in Go and Laravel show the minimum.
Zero Trust and NIST SP 800-207 Must-know
In plain words: being on the office network or the production VPC proves nothing; every request proves itself, and access ends when trust ends.
Common misunderstanding: "Zero Trust means trusting no one, so we need a VPN everywhere." Zero Trust moves the control from the network edge to the resource: authenticate and authorize every request, with least privilege. A VPN is a perimeter tool and fits the old model.
Definition: NIST SP 800-207 lists seven tenets (abridged): (1) all data sources and computing services are considered resources; (2) all communication is secured regardless of network location, and "network location alone does not imply trust"; (3) access to individual resources is granted per session, with least privileges; (4) access is determined by dynamic policy, including the observable state of client identity, application and requesting asset, and may include behavioural and environmental attributes; (5) the enterprise monitors and measures the integrity and security posture of all owned and associated assets, "no asset is inherently trusted"; (6) all resource authentication and authorization are dynamic and strictly enforced before access is allowed, a "constant cycle of obtaining access, scanning and assessing threats, adapting, and continually reevaluating trust"; (7) the enterprise collects as much information as possible about the current state of assets, network infrastructure and communications and uses it to improve its posture. The logical components are the policy engine, policy administrator and policy enforcement point.
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 restoredReal scenarios: an identity-aware proxy in front of internal apps; mTLS between services with SPIFFE-style identities; per-request authorization in microservices instead of "internal network, trusted"; conditional access that denies sign-in from non-compliant devices.
| NIST tenet theme | What you implement | Product examples |
|---|---|---|
| Never trust the network | PEP at every resource; mTLS between services | Envoy, Istio, Linkerd, identity-aware proxies |
| Verify explicitly | Strong authentication plus device and context | OIDC providers, WebAuthn, MDM |
| Least privilege | Narrow permissions, just-in-time and time-boxed grants | AWS IAM Identity Center, spatie roles with expiry |
| Continuous verification | Session re-evaluation, short-lived tokens | Token lifetimes in minutes, CAEP style events |
| Assume breach | Segmentation, logging, anomaly detection | SIEM, network policies |
Fix / how to use it: start with the resources, not the network: inventory them, put a PEP in front of each, define attributes (user, device, risk), and make the first policy "deny unless an explicit rule permits".
Zero Trust in practice: BeyondCorp, ZTNA, device posture, mTLS Important
In plain words: Google stopped treating its internal network as trusted and made access depend on user and device, and the industry turned that into products.
Common misunderstanding: "ZTNA replaces the VPN and that is Zero Trust." ZTNA (Zero Trust Network Access) is an industry term for gateway-style access to applications without network-level access; it covers part of the architecture. NIST SP 800-207 itself describes approaches such as enhanced identity governance, micro-segmentation and network infrastructure with software defined perimeters; it does not use the acronym ZTNA (the saved copy of the PDF has no match).
Definition: BeyondCorp (Ward and Beyer, 2014) moved access control "from the perimeter" to individual devices and users; the 2016 follow-up, "Design to Deployment at Google", describes "an access model with dynamic tiers of trust for devices". Device posture is the signal set about the client: managed or not, OS version and patches, disk encryption, screen lock, attestation. Continuous verification re-checks these during the session. Service to service, the identity is a workload certificate (see Mutual TLS & Securing Service-to-Service Traffic and Service Mesh & the Sidecar Pattern), and authorization policies in the mesh (an Istio AuthorizationPolicy, an Envoy RBAC filter) are PEP and PDP together.
| Layer | Identity | Authorization | Example |
|---|---|---|---|
| User to app | OIDC login, MFA, device certificate | App policy plus device tier | Identity-aware proxy |
| App to app | Workload certificate (mTLS) | Mesh policy by service identity | Istio, Linkerd |
| App to data | Database role or short-lived credentials | Row-level security, column grants | PostgreSQL roles and RLS |
| Admin access | Just-in-time elevation | Time-boxed role grant | Break-glass role with expires_at |
Fix / how to use it: add device attributes to the PEP request (Env["device_managed"]), make the policy forbid on bad posture (see forbid-unmanaged-device in the ABAC rules) and keep sessions and tokens short.
Mechanics
Knobs and where they live
| Product | Knob | Meaning | Default or note |
|---|---|---|---|
| Laravel Gate | Gate::before / Gate::after | Run before or after every ability check; non-null result is final | Return null to fall through |
| Laravel Policy | before(User, string $ability) | Per-policy short circuit | Return null to fall through |
| Laravel | Gate::guessPolicyNamesUsing | Custom policy discovery | Default: Policies directory next to models, Policy suffix |
| Laravel | #[UsePolicy(...)] attribute | Bind a model to its policy | Alternative to Gate::policy |
| Laravel route | can:update,post middleware alias | Authorizes before the controller | Alias registered by Laravel |
| spatie/laravel-permission | assignRole, givePermissionTo, hasPermissionTo | Roles and permissions on the user | hasPermissionTo bypasses the Gate, so Gate::before does not apply |
| OPA | default allow := false | Make the rule defined when nothing matches | Without it the result is undefined |
| OPA REST | POST /v1/data/<path> with {"input": ...} | Evaluate a rule | 200 without result when undefined; 400 on bad input |
| Cedar | permit, forbid, when, unless | Effect and conditions | Deny unless some permit matches and no forbid matches |
| OpenFGA | consistency MINIMIZE_LATENCY or HIGHER_CONSISTENCY | Cache vs freshness | MINIMIZE_LATENCY |
| OpenFGA SDK | AuthorizationModelId | Pin a model version | Unset uses the latest |
| SpiceDB | consistency on a request | minimize_latency, at_least_as_fresh, at_exact_snapshot, fully_consistent | Default minimize_latency for most APIs |
| PostgreSQL | FORCE ROW LEVEL SECURITY | Apply policies to the table owner | Owners are exempt otherwise |
| PostgreSQL | set_config('app.tenant_id', v, true) | Transaction-local setting | true = local; safe with pools |
Request flow and where each failure lands
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 changesError names you will see
| Where | Name or message | Meaning |
|---|---|---|
| Laravel | Illuminate\Auth\Access\AuthorizationException (HTTP 403) | Gate::authorize denied |
| Laravel | Response::denyAsNotFound() | Denied with status 404 |
| Laravel | Response::denyWithStatus(404) | Denied with a custom status |
| spatie | Spatie\Permission\Exceptions\UnauthorizedException | Raised by the package's own middleware |
| OPA | HTTP 200 with {} | Rule undefined: treat as deny |
| OPA | HTTP 400 | Invalid input document |
Go rbac | ErrSSD, ErrDSD, ErrCycle | Constraint or hierarchy violations |
Go rebac | ErrDepth | Evaluation deeper than MaxDepth (25) |
Go httpguard | ErrUndefined | OPA answered without a result |
| OAuth | insufficient_scope | Token lacks the scope; bearer-token error |
| PostgreSQL | new row violates row-level security policy for table "invoices" (SQLSTATE 42501) | WITH CHECK rejected a write |
Go
The Go module (go/, module academy/authorization-rbac-abac-zero-trust) has one package per model, all behind the same authz.Decider interface, so a handler does not care whether the answer comes from roles, attributes or relationships. Dependencies: only cedar-go and the OpenFGA go-sdk (both of which require Go 1.26 in their go.mod, so this module says go 1.26.0).
Example: the shared vocabulary
// 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} }Example: RBAC with hierarchy and separation of duties
// 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
}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")
}
}Example: ABAC rules with deny-overrides
// 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()) }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)
}
}
}Example: ReBAC (the Zanzibar model in process)
The evaluator is the code shown in the ReBAC block. Its tests reproduce the paper's Figure 1 configuration, usersets, parents, cycles, exclusion and the new enemy problem.
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")
}
}Example: the enforcement point, a decision cache and an OPA client
// 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
}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")
}
}Example: Cedar and OpenFGA adapters
// 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
}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)
}
}// 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
}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)
}
}The Go angle
Go has no authorization framework in the standard library, so the pattern is a small interface (Decider) and middleware. Put the PEP in net/http middleware (or a gRPC interceptor), pass the request context.Context to the PDP so timeouts propagate, fail closed on any error, and test the matrix with table tests. cedar-go runs Cedar in process (microsecond decisions, no network), OPA is normally a sidecar reached over its REST Data API, and OpenFGA or SpiceDB are central services reached with their SDKs; the fga adapter compiles against the real SDK and is unit-tested through the Checker seam, but it was not run against a live server.
Laravel
Laravel 13 ships the PEP and a small PDP: the Gate (closures and the Gate::before hook), Policies (one class per model, discovered by naming convention or the #[UsePolicy] attribute), Gate::authorize in code, the can middleware alias on routes, @can in Blade, and Response::deny / denyAsNotFound for reasons and statuses. For roles and permissions as data, spatie/laravel-permission adds the tables, the HasRoles trait and Gate integration; its package versions 7 and 8 list Laravel 12 and 13 as supported.
Example: a Policy that is also an ABAC rule
<?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
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');
});
}
}Example: Gate::before, a plain Gate and a ReBAC Gate
<?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
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();
}
}Example: routes, controller and tenant middleware
<?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
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
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);
});
}
}Example: spatie/laravel-permission as the RBAC store
<?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
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
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
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));
}
}The Laravel angle
Use Policies for object rules (they are the ABAC layer), spatie permissions for who holds which capability (the RBAC layer), and a ReBAC check or service for sharing (tuples). The route middleware can:update,document is the first PEP; Gate::authorize inside the controller is the second, and it still protects the code when the route is reused by a job or a console command. The documented spatie advice is to handle super-admin with Gate::before or Gate::after and to check permissions (can()), not roles, everywhere else; the package warns that calling hasPermissionTo() directly bypasses the Gate, so the super-admin shortcut does not apply there. Return null from before to fall through; returning false from a policy before denies everything, which is how the suspended-user rule works. Eloquent global scopes (the tenant scope) do not apply to DB::table() queries, so the database row-level security backstop in SQL matters. The PHP files were syntax-checked with php -l only: they are excerpts that assume a standard Laravel 13 app with the spatie migration published; the Laravel tests were not run.
SQL: roles, permissions and relation tuples
-- 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);-- 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;-- 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 | Question | Cost shape |
|---|---|---|
| 1 | Effective permissions of a user | Recursive CTE over the hierarchy; cache the result per user |
| 2 | Does the user hold one permission | Same CTE with EXISTS |
| 3 | Would this grant violate separation of duties | Two EXISTS; run inside the grant transaction |
| 4 | Direct ReBAC check | One primary key lookup |
| 5 | One userset hop | One join on the primary key prefix |
| 6 | List what a user can see (direct and group) | Index range scan on the reverse index plus group join |
| 7 | Tenant isolation | Planner adds the policy predicate to every query on the table |
Deeper nesting (a group inside a group, folders inside folders) turns query 5 into a recursive CTE with a depth limit; at that point a dedicated engine (OpenFGA, SpiceDB) is cheaper than maintaining the SQL.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost or limit |
|---|---|---|---|---|
| IDOR: user edits an id in the URL | Object-level check on every access | Policy or ReBAC check with the object, not just a role | Closes the top OWASP class | One more call per object |
| Role explosion | Add attributes or relationships | ABAC rule or ReBAC tuple instead of a new role | Fewer roles | Needs policy tests |
| Revoked permission still works | Short TTL plus versioned cache keys, zookies for content | Bump version on write; pass the zookie | Bounded staleness | Cache complexity |
| "What can this user see?" is slow | Reverse index or ListObjects | relation_tuples_by_subject, SpiceDB LookupResources | One query | Index writes |
| Super-admin everywhere | Gate::before returns true for the role | Check permissions elsewhere | One place | Audit it; log use |
| Cross-tenant leak | Tenant in policy, scope and row-level security | Three layers | Defense in depth | Pool and owner bypass pitfalls |
| Confused deputy (a service acts with its own broad rights) | Propagate the end user as the subject | Pass identity and check at the data service | Least privilege | Plumbing |
| Policy engine outage | Fail closed; cache positives briefly; embed critical rules | Cedar or a library in process for core paths | Safety | Some features unavailable |
| Over-broad service accounts | Per-service identity and narrow grants | mTLS identity plus mesh policy | Least privilege | Many identities to manage |
Fixing a stale revoke, step by step
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 DENYChoosing
Which model for which product
| Product type | Primary model | Add | Reason | Avoid |
|---|---|---|---|---|
| Internal admin tool, 3 roles | RBAC (Laravel Gate plus spatie) | Policy for object rules | Few roles, easy audit | A policy engine |
| Consumer app (profiles, posts) | Ownership rules in Policies | Rate limits, blocked-user relation | Simple "owner or public" | Roles per user |
| B2B SaaS (organizations, projects) | RBAC per tenant (org roles) plus tenant isolation | ReBAC for project and resource sharing | Org roles are few; sharing is relational | Global roles without tenant |
| Document sharing, folders, links | ReBAC (OpenFGA, SpiceDB) | Attributes for link expiry | Inheritance and nested groups | Per-document ACL tables with N joins |
| Regulated data (health, finance) | ABAC (Cedar, OPA) | RBAC for coarse access, audit log | Context rules (purpose, device, time) | Free-form code checks |
| Microservice platform | Mesh policy plus per-service authz | OPA sidecar, mTLS identity | Service identity and Zero Trust | Trusting the internal network |
| Public API for partners | OAuth scopes plus per-resource checks | Per-client rate limits | Delegation plus object checks | Scope as the only check |
Which engine
| Situation | Choose | Why |
|---|---|---|
| Laravel monolith, roles and policies | Gates, Policies, spatie | Built in, testable, no new service |
| Many languages, central policy, attributes | OPA (Rego) | One policy engine, sidecar or library |
| Embedded, analyzable, default-deny | Cedar (cedar-go, Verified Permissions) | Schema validation, forbid wins |
| Sharing and nested groups at scale | OpenFGA or SpiceDB | Tuples, ListObjects, consistency tokens |
| One database, simple tenant isolation | PostgreSQL RLS plus a policy layer | Backstop for every query path |
In architecture: from a single process to a distributed system
Monolith: one process, one database
A Laravel monolith with the Gate and Policies is enough: one PEP (the can middleware), one PDP (the Policy classes), one PIP (the Eloquent models), one PAP (the code in Git). Keep the tenant scope in the model, add spatie roles when the permission list grows, and put row-level security under it as the backstop.
Modular monolith: boundaries without the network
Each module owns its policies (billing decides invoices, documents decides documents) and exposes an authorization method as its public API; no module reads another module's role tables. A shared Request and Decision type (as in authz.go) keeps modules decoupled, and a module that needs another module's relationships calls its public method, not its tables.
Microservices: every arrow is a decision
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 tenantThe gateway cannot know object ownership; each service must still check objects. Forward the end-user identity (not only the service identity) to avoid the confused deputy problem. The mesh enforces who may call whom (Service Mesh & the Sidecar Pattern, Mutual TLS); the service enforces what the user may do (Service Communication).
Distributed data: replicas, caches, regions
A replicated authorization store needs the same discipline as any replicated data (Consistency Models): permission writes go to one place, and reads that guard content need a token that proves the read is at least as fresh as the content. Zanzibar replicates ACL data to "tens of geographically distributed data centers" and uses zookies and Spanner timestamps for that. A decision cache is itself a replica: its TTL is your revocation latency, so choose it per resource class (Caching).
Scaling path: 1x, 10x, 100x
| Load | Design | What changes |
|---|---|---|
| 1x: one app, thousands of users | Gate, Policies, spatie, tenant scope | Nothing external |
| 10x: many tenants, sharing features | Tuples table with reverse index, decision cache with versioned keys | Move relationships out of ad hoc tables |
| 100x: many services, many regions | OpenFGA or SpiceDB cluster (or Zanzibar-class), OPA sidecars, zookies stored with content | Central relationship store, consistency tokens, batch checks, ListObjects for lists |
| Always | Default deny, audit log, policy tests in CI | Never relaxed |
Lab: policies, constraints and a stale snapshot
Experiment 1: run the in-process lab (run)
cd docs/snippets/system-design/authorization-rbac-abac-zero-trust/go
go run ./cmd/labroles 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 performedThe four lines show: 72 role combinations vs 3 attribute checks; the SSD violation message; the same Check true at the old snapshot and false at the zookie; and the listing cost (1,001 point checks for 1,001 documents), the reverse-index problem in numbers.
Experiment 2: the Go tests (run)
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 .../rebacExperiment 3: the Rego tests with OPA (run)
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/3Experiment 4: the Laravel policy and spatie against a database (expected, not run)
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)Experiment 5: OpenFGA with the model file (expected, not run)
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)Common misconceptions
| Belief | Reality |
|---|---|
| A valid token means the request is allowed | It proves identity and claims; the object decision is separate |
| RBAC is outdated | It is the coarse layer of most systems; ABAC and ReBAC refine it |
| ABAC means no roles | A role is one attribute |
| More roles give finer control | Past a point they cause role explosion and unreviewable grants |
| The policy engine blocks requests | The PEP blocks; the PDP only answers |
| ReBAC needs a graph database | Zanzibar uses flat tuples in a normal store |
| Eventual consistency is fine for permissions | Stale ACLs create the new enemy problem |
| OAuth scopes are the user's permissions | Scopes are delegation by the user to a client |
| The gateway authorizes everything | It cannot know objects; services must check them |
| Zero Trust is a product | It is a set of principles (NIST SP 800-207); products implement parts |
| Admin check without a tenant id is safe | An admin of tenant A must not read tenant B |
| Hide the button and the endpoint is safe | The server must enforce every call |
Cheat sheet
| Topic | Remember |
|---|---|
| Order | Authenticate, then authorize; 401 vs 403 vs 404 |
| Default | Deny unless a rule permits; fail closed on errors |
| PEP vs PDP | The PEP enforces; the PDP decides; PIP supplies facts; PAP holds policies |
| RBAC | Check permissions, grant through roles; keep roles few |
| SSD vs DSD | SSD at assignment, DSD at session activation |
| ABAC | Subject, resource, action, environment attributes; forbid wins |
| ReBAC | Tuples object#relation@subject; rewrite rules; zookies for freshness |
| Listing | A reverse-index problem; do not run N checks |
| Tenants | Tenant id in policy, ORM scope and row-level security; 404 across tenants |
| Scopes | Intersection of user permissions and client scopes |
| Caching | TTL is the revocation window; versioned keys; never cache errors |
| Audit | Log decision, policy ids, versions; log grant changes |
| Zero Trust | No trust from network location; per-session, continuously verified, least privilege |
| Laravel | Policies for objects, spatie for permissions, Gate::before for super-admin |
| Go | Decider interface, middleware PEP, table tests |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — Why can a valid JWT still produce a 403? Must-know
Answer
Answer: Authentication proves identity and claims; authorization evaluates whether this subject may perform this action on this resource, using roles, attributes or relationships and possibly fresher data than the token.
2 — Which XACML component enforces a decision and which makes it? Good to know
Answer
Answer: The PEP enforces (middleware, gateway, Gate); the PDP decides (OPA, Cedar, SpiceDB, a Policy class). The PIP supplies attributes and the PAP manages policies.
3 — What is role explosion and two ways to reduce it? Important
Answer
Answer: One role per combination of attributes (72 for 6 x 4 x 3). Add attribute rules (ABAC) or relationship tuples (ReBAC), use hierarchies and permission-based checks.
4 — Static vs dynamic separation of duties? Good to know
Answer
Answer: Static forbids assigning conflicting roles to one user at all; dynamic allows both assignments but forbids activating both in the same session.
5 — What does doc:readme#viewer@group:eng#member mean? Good to know
Answer
Answer: A relation tuple: members of group eng (a userset) are viewers of doc readme.
6 — What is the new enemy problem and what fixes it? Important
Answer
Answer: Applying a stale ACL to new content (or ignoring ACL update order) so a removed user sees new content. Zookies and snapshot reads at least as fresh as the content version fix it.
7 — Why is "list what I can see" harder than a check? Important
Answer
Answer: A check walks from one object; listing walks backwards from the subject, so it needs a reverse index, ListObjects or LookupResources, or a join in SQL.
8 — How do OAuth scopes and permissions combine? Must-know
Answer
Answer: Effective access is the intersection: the user must have the permission and the client must hold the scope.
9 — Which three layers protect tenants? Must-know
Answer
Answer: The policy (tenant mismatch forbids), the ORM scope, and database row-level security with FORCE; plus 404 for cross-tenant ids and tenant ids in cache keys.
10 — What does returning null from Laravel's Gate::before do? Important
Answer
Answer: It falls through to the normal checks; only a non-null result is final.
11 — What are the NIST SP 800-207 ideas in one line each? Good to know
Answer
Answer: No trust from network location, per-session least-privilege access, dynamic policy using identity, device and behaviour, continuous monitoring of asset posture, strict enforcement before access, and collecting data to improve policy.
12 — Why must the PEP fail closed? Must-know
Answer
Answer: If an error becomes an allow, an attacker who can disturb the PDP gains access; a 503 is safer than a wrong 200.
Glossary
| Term | Meaning |
|---|---|
| Authorization | Deciding whether a subject may perform an action on a resource |
| Access control | The mechanisms that enforce authorization |
| Authentication | Establishing who the subject is |
| PEP | Policy Enforcement Point: intercepts and enforces |
| PDP | Policy Decision Point: evaluates policies |
| PIP | Policy Information Point: supplies attributes |
| PAP | Policy Administration Point: manages policies |
| XACML | OASIS XML standard for attribute policies and architecture |
| ALFA | Abbreviated Language for Authorization, compact syntax over XACML |
| ACL | Access control list attached to an object |
| RBAC | Role-based access control |
| NIST RBAC | The reference model, ANSI/INCITS 359 |
| Role | A named set of permissions tied to a job function |
| Permission | An operation on a kind of object |
| Role hierarchy | Senior roles inherit junior permissions |
| Separation of duties | Constraint that conflicting roles must not combine (SSD at assignment, DSD per session) |
| Role explosion | Too many roles from attribute combinations |
| ABAC | Attribute-based access control (NIST SP 800-162) |
| Attribute | Name and value on subject, resource, action or environment |
| Policy | A rule that permits or forbids under conditions |
| OPA | Open Policy Agent, general policy engine |
| Rego | OPA's policy language |
| Cedar | AWS-originated policy language with permit and forbid |
| ReBAC | Relationship-based access control |
| Zanzibar | Google's global authorization system (USENIX ATC 2019) |
| Relation tuple | object#relation@subject fact |
| Userset | A subject that is itself object#relation |
| Rewrite rule | Definition of a relation from others (this, computed_userset, tuple_to_userset) |
| Check | API: does subject have relation on object |
| Expand | API: effective userset of an object relation |
| List objects | Reverse query: objects a subject can reach |
| Zookie | Opaque consistency token (Zanzibar); SpiceDB calls it ZedToken, a snapshot token |
| OpenFGA | CNCF Zanzibar-style authorization server |
| SpiceDB | AuthZed's Zanzibar-inspired database |
| Keto | Ory's open-source permissions server |
| Permify | Zanzibar-inspired authorization service |
| Capability | Unforgeable reference granting authority |
| Macaroon | Bearer credential with chained contextual caveats |
| Multi-tenancy | Many customers sharing one system |
| Tenant id | Column and key that identifies the customer |
| Row-level security | PostgreSQL per-row policies enforced by the database |
| Scope vs permission | Scope is client delegation; permission is user right |
| Policy as code | Policies in version control with tests and CI |
| Policy testing | Automated permit and deny matrices for policies |
| Decision caching | Reusing recent decisions; TTL is the revocation window |
| Reverse index | Index from subject to objects, for listing |
| Audit log | Record of decisions and grant changes |
| Explainability | Ability to say why a decision was made |
| Zero Trust | No implicit trust from network location; verify per request |
| NIST SP 800-207 | Zero Trust Architecture publication |
| BeyondCorp | Google's zero trust access model |
| ZTNA | Zero Trust Network Access, gateway style access to applications |
| Device posture | Health and management state of the client device |
| Continuous verification | Re-evaluating trust during a session |
| Least privilege | Only the access needed for the task |
| Gate | Laravel's authorization entry point for abilities |
| Policy (Laravel) | Class with per-model authorization methods |
| authorize | Gate::authorize: throws on denial |
| can middleware | Route alias that authorizes before the controller |
| Gate::before | Hook run before every check; non-null result is final |
| spatie/laravel-permission | Package storing roles and permissions for Laravel |
References
- NIST SP 800-207, Zero Trust Architecture (August 2020): https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-207.pdf
- NIST SP 800-162, Guide to Attribute Based Access Control (January 2014): https://nvlpubs.nist.gov/nistpubs/specialpublications/NIST.SP.800-162.pdf
- NIST RBAC project: https://csrc.nist.gov/projects/role-based-access-control
- Zanzibar: Google's Consistent, Global Authorization System (USENIX ATC 2019): https://research.google/pubs/zanzibar-googles-consistent-global-authorization-system/ and https://storage.googleapis.com/gweb-research2023-media/pubtools/5068.pdf
- BeyondCorp: A New Approach to Enterprise Security: https://research.google/pubs/beyondcorp-a-new-approach-to-enterprise-security/
- BeyondCorp: Design to Deployment at Google: https://research.google/pubs/beyondcorp-design-to-deployment-at-google/
- Macaroons (NDSS 2014): https://research.google/pubs/macaroons-cookies-with-contextual-caveats-for-decentralized-authorization-in-the-cloud/
- OWASP Authorization Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html
- RFC 6749, OAuth 2.0 (section 3.3, scope): https://datatracker.ietf.org/doc/html/rfc6749
- OpenFGA concepts: https://openfga.dev/docs/concepts ; modeling: https://openfga.dev/docs/modeling/getting-started ; consistency: https://openfga.dev/docs/interacting/consistency ; ListObjects: https://openfga.dev/docs/getting-started/perform-list-objects
- SpiceDB schema: https://authzed.com/docs/spicedb/concepts/schema ; consistency: https://authzed.com/docs/spicedb/concepts/consistency ; commands: https://authzed.com/docs/spicedb/concepts/commands
- Ory Keto: https://www.ory.sh/docs/keto ; Permify: https://docs.permify.co/
- Open Policy Agent: https://www.openpolicyagent.org/docs ; policy language: https://www.openpolicyagent.org/docs/policy-language ; REST API: https://www.openpolicyagent.org/docs/rest-api ; decision logs: https://www.openpolicyagent.org/docs/management-decision-logs ; testing: https://www.openpolicyagent.org/docs/policy-testing
- Cedar: https://docs.cedarpolicy.com/ ; policy syntax: https://docs.cedarpolicy.com/policies/syntax-policy.html ; schema: https://docs.cedarpolicy.com/schema/schema.html ; authorization: https://docs.cedarpolicy.com/auth/authorization.html
- Laravel 13 authorization: https://laravel.com/docs/13.x/authorization ; Eloquent global scopes: https://laravel.com/docs/13.x/eloquent#global-scopes ; middleware: https://laravel.com/docs/13.x/middleware
- spatie/laravel-permission: https://spatie.be/docs/laravel-permission/v6/introduction ; prerequisites: https://spatie.be/docs/laravel-permission/v8/prerequisites ; roles and permissions: https://spatie.be/docs/laravel-permission/v8/basic-usage/role-permissions ; super-admin: https://spatie.be/docs/laravel-permission/v8/basic-usage/super-admin
- PostgreSQL row security policies: https://www.postgresql.org/docs/current/ddl-rowsecurity.html
- Go: https://pkg.go.dev/github.com/openfga/go-sdk/client ; https://pkg.go.dev/github.com/cedar-policy/cedar-go ; https://pkg.go.dev/github.com/open-policy-agent/opa/v1/rego