24 Identity Management and Access Control: RBAC vs. ABAC
24.2.2 Why you should care: Broken Access Control is OWASP #1 |
24.2.3 The maintenance problem: authorization as scattered if-statements |
24.8.1 The architecture: separating decision from enforcement |
These notes draw on the reference materials in the course’s
rbac-abac folder—
24.1 Learning Objectives
By the end of this lecture you should be able to:
Distinguish authentication from authorization, and place both inside the broader discipline of Identity and Access Management (IAM).
Define the four classic access control models—
DAC, MAC, RBAC, ABAC— and identify which one a given system uses. Explain RBAC precisely: users, roles, permissions, the three NIST rules, role hierarchies, and the “role explosion” failure mode.
Explain ABAC precisely: subject, resource, action, and environment attributes, and the if/then policy style they enable.
Choose between RBAC, ABAC, or a hybrid for a given scenario, and defend the choice with the trade-offs each model carries.
Read and write Cedar policies—
effect, scope, conditions— and predict the outcome of an authorization request under Cedar’s evaluation semantics (default deny; forbid overrides permit). Trace a real request through TinyTodo, the Cedar example application, from HTTP handler to is_authorized to policy evaluation to Allow/Deny.
Build and test a policy-as-code authorization layer in Python using cedarpy, keeping policy out of application code so it can change without redeploying.
24.2 Motivation: The Login Is Not the Lock
24.2.1 Authentication vs. authorization
Every secured system answers two different questions, and confusing them is the root of half the access-control bugs in the wild:
Authentication (authN): Who are you? Verifying identity—
password, SSO, MFA, biometrics, an API token. Authorization (authZ): What are you allowed to do? Deciding whether this verified identity may perform this action on this resource.
Logging in is authentication. Everything after—
Both live inside Identity and Access Management (IAM)—
24.2.2 Why you should care: Broken Access Control is OWASP #1
Recall from the OWASP notes that Broken Access Control is the
#1 web application security risk. Not exotic cryptography
failures—
@app.get("/lists/{list_id}")
def get_list(list_id: int, user: User = Depends(current_user)):
return db.get_list(list_id) # BUG: any logged-in user can read ANY listThe user is authenticated. The authorization check simply isn’t
there. This lecture is about doing that check
systematically—
24.2.3 The maintenance problem: authorization as scattered if-statements
Most apps start with authorization hard-coded inline:
if user.role == "admin" or (user.id == lst.owner_id) or \
(user.id in lst.editors and action != "delete"):
...This works—
Duplication: every service re-implements the same rules; each copy drifts.
Change is expensive: a new rule (“TAs can grade, but only their own section”) means hunting down and editing every check in every service, then redeploying all of them.
No auditability: “who can access what?” requires reading the entire codebase. Compliance auditors do not enjoy this, and neither will you.
The fix the industry converged on is policy-as-code: pull
authorization rules out of application code into declarative
policies evaluated by a dedicated engine. Your app asks a question
(“may Alice delete List 7?”) and enforces the answer; the
rules live elsewhere, in one reviewable, testable,
versionable place. Cedar—
Where you’ve seen this pattern before: it’s the
layered-architecture lecture all over again. We separated routes
from business logic from data access; now we separate policy
from code. Same principle—
24.3 Running Example: TinyTodo
We need one example rich enough to exercise every concept, and we’ll use it for the rest of the lecture: TinyTodo, the official Cedar example application (the full source is in the course folder under rbac-abac/tinytodo/).
TinyTodo is a shared task-list app:
Users create Lists and fill them with tasks.
Teams group users. Teams can nest: a team can be a member of another team.
A list’s creator is its owner. Owners can share a list in two modes: reader (view the list and its tasks) or editor (view, plus add/edit/check/delete tasks).
The out-of-the-box population (from entities.json):
Application::"TinyTodo" |
(parent of everything) |
| |
+-----------+-------+--------+------------+ |
| | | | |
Team::"admin" Team::"temp" User::"kesha" ... |
| | |
User::"emina" +------------------+ |
| | |
Team::"interns" User::"andrew" |
| |
User::"aaron" |
Figure 1: TinyTodo users and teams. Edges point from member
to parent. aaron is in interns; interns is in
temp; therefore aaron is (transitively) in temp.
Note the direction: kesha is in neither—
TinyTodo is a Rust HTTP server plus a Python CLI. The server holds
the data and the policies; every command a user issues is
authorized by the Cedar engine before the server acts (never trust
the client—
>>> set_user(andrew)
>>> create_list("Cedar blog post")
Created list ID 0
>>> share_list(0, interns, read_only=True)
Shared list ID 0 with interns as reader
>>> set_user(aaron)
>>> get_list(0) # allowed: aaron is in interns, interns are readers
=== Cedar blog post ===
>>> toggle_task(0, 1)
Access denied. User aaron is not authorized to Toggle Task on [0, 2]
>>> set_user(kesha)
>>> get_list(0)
Access denied. User kesha is not authorized to Get List on [0]Hold these three outcomes in your head—
TinyTodo’s permission rules, in English:
Any user may create lists and enumerate their own lists.
A list’s owner may do anything to it.
A list’s readers and editors may view it.
A list’s editors may modify it and its tasks.
Notice something: the last two rules look like roles (reader,
editor—
24.4 Access Control Fundamentals
24.4.1 The universal triple: principal, action, resource
Every authorization question, in every model, in every system ever built, has the same shape:
May this principal (subject: user, service, AI agent) perform this action (operation: read, write, delete, approve) on this resource (object: file, row, list, endpoint)?
Sometimes there’s a fourth element: context—
24.4.2 Two principles worth tattooing somewhere
Least privilege: grant the minimum access needed to do the job, nothing more. Every excess permission is free attack surface.
Default deny: if no rule explicitly allows a request, deny it. The dangerous failure mode is silence being interpreted as consent. (Cedar enforces default deny at the engine level—
a request is allowed only if some permit policy explicitly matches.)
24.4.3 The four classic models
Model | Access decided by | Who controls it | Example |
DAC (Discretionary) | the resource's owner, at their discretion | resource owners | Unix file permissions, Google Doc sharing |
MAC (Mandatory) | central policy over labels/clearances | a central administrator | military/government classified systems |
RBAC (Role-Based) | the principal's role(s) | admins define roles | admins can delete; viewers can read |
ABAC (Attribute-Based) | attributes of principal, resource, action, environment | policy authors | TAs may grade their own section, before the deadline |
DAC and MAC are the historical bookends (maximally decentralized
vs. maximally centralized). Modern applications overwhelmingly
choose between—
24.5 Role-Based Access Control (RBAC)
24.5.1 Definition
Formal definition. RBAC is an authorization model in which permissions are assigned to roles, and roles are assigned to users. A user’s access rights are exactly the union of the permissions of their roles. Developed in the early 1990s (and later standardized by NIST) to tame the growing mess of per-user permission grants in large systems.
Plain English. You never say “Alice can delete invoices.” You say “Accountants can delete invoices” and “Alice is an Accountant.”
The three components:
Users—
individuals (or services) needing access. Roles—
named job functions: Admin, Editor, Viewer, TA, Instructor. A role is a bundle of permissions. Permissions—
specific rights on resources: read patient records, deploy to staging, approve trades.
The three NIST rules that make a system genuinely RBAC:
Role assignment—
a user can exercise a permission only if they’ve been assigned a role. No role, no rights. Role authorization—
the user’s active role must be one they’re authorized to hold (you can’t just claim Admin). Permission authorization—
permissions are exercised only through roles, never granted directly to individuals.
Rule 3 is the load-bearing one. The moment you grant one user one direct permission “just this once,” you’ve forked your access model and auditing becomes archaeology.
Intuition. RBAC is the theater-badge system: your badge says
CREW or PRESS or VIP, and every door guard checks the badge, not
your biography. Hiring means issuing a badge; role change means
swapping badges; leaving means surrendering the badge—
24.5.2 Worked example: TinyTodo’s reader/editor roles
TinyTodo’s sharing model is RBAC in miniature. Each list has two
per-list groups—
rule: editors of a list may CreateTask on it
assignment: Team::"interns" is in list 0’s readers
membership: aaron is in Team::"interns"
When andrew ran share_list(0, interns, read_only=True), no permission was written anywhere near aaron. The server simply added list 0’s readers-team as a parent of Team::"interns". aaron’s later get_list(0) succeeds by pure role reasoning: aaron ∈ interns ∈ readers-of-list-0, and readers may read. One membership edge changed; a whole team’s access changed with it. That’s the RBAC efficiency story in one move.
24.5.3 RBAC variants: the four NIST levels
NIST defines four cumulative levels, each adding structure to the previous:
Flat RBAC—
users have roles, roles have permissions. That’s it. (TinyTodo’s reader/editor is flat RBAC.) Hierarchical RBAC—
roles inherit: a senior role automatically includes junior roles’ permissions. Admin ⊇ Editor ⊇ Viewer, so you never re-list read permissions in the Admin role. (In Cedar you build this with parent chains: make Role::"Admin" a member of Role::"Editor", which is a member of Role::"Viewer".) Constrained RBAC—
adds separation of duties: constraints prevent one person holding conflicting roles. The Snowflake finance example: traders execute trades, managers approve them, compliance reviews them— and no user may hold two of those roles at once, or one insider could do all three steps of a fraud alone. Symmetric RBAC—
adds mandatory periodic permission review: role–permission assignments are audited and pruned on a schedule, so roles don’t accumulate rights forever.
24.5.4 Why RBAC wins (when it wins)
Simplicity and speed. Checks are cheap (“is user in role?”) and rules are legible to non-engineers.
Lifecycle management. New hire → assign roles, done in hours not days. Job change → swap roles. Departure → remove roles, all access gone at once. No per-user permission archaeology.
Compliance. HIPAA, GDPR, SOX auditors want a clear, auditable answer to “who can access what and why.” A role table is that answer. In healthcare: Doctor reads and updates medical records; Receptionist sees contact details and schedules only. The role names document the security model.
24.5.5 Where RBAC cracks: role explosion
Common misconception: “If we need finer-grained control, we
just add more roles.” Follow that instinct and you get role
explosion—
Watch it happen. Your company needs department-specific access:
Engineer, Accountant. Then location matters:
Engineer-NYC, Engineer-Remote, Accountant-NYC...
Then seniority: Senior-Engineer-NYC... With 4 departments × 5
locations × 3 levels you’re at 60 roles, and someone just asked for
time-of-day restrictions. Hundreds or thousands of roles later,
nobody can say what any of them actually grant—
Practical implication. RBAC is your default. It covers most
applications most of the time, cheaply and legibly. Reach past it
when your access rules genuinely depend on properties that
vary per-request or per-resource—
24.6 Attribute-Based Access Control (ABAC)
24.6.1 Definition
Formal definition. ABAC is an authorization model in which
access decisions are computed from attributes—
The four attribute categories:
Category | Examples |
Subject (user) attributes | job title, department, seniority, training completed, location, clearance |
Resource attributes | file type, creator/owner, sensitivity label, project phase, grade's section |
Action attributes | read vs. write vs. delete vs. approve |
Environment attributes | time of day, date, IP/network, device type, MFA status, risk score |
Plain English. Instead of “what badge do you wear?”, ABAC asks “what is true about you, about the thing you’re touching, and about right now?”
Policies read as if/then statements (Okta’s examples):
If the user is in accounting, then they may access accounting files.
If the user is a manager, then they may read and write files.
If company policy says “no Saturday work” and today is Saturday, then nobody may access anything.
Intuition. ABAC is the nightclub bouncer with a checklist
instead of a guest list: over 18? dress code? not already flagged
tonight? before last entry? The same person gets different
answers on different nights—
24.6.2 Worked example: TinyTodo’s location guardrail
TinyTodo’s users carry attributes—
"User::\"aaron\"": {
"location": "ABC17",
"joblevel": 5,
"parents": ["Team::\"interns\"", "Application::\"TinyTodo\""]
}The tutorial’s Policy 6 is a textbook ABAC rule (we’ll parse the syntax in Policy-as-Code with Cedar; read it as English for now):
// No access unless high-rank at a DEF site, or co-located with the list's owner
forbid (principal, action, resource is List)
unless {
principal.joblevel > 6 && principal.location like "DEF*" ||
principal.location == resource.owner.location
};The consequences are striking. Kesha (location ABC17) creates a list and explicitly shares it with Andrew (location XYZ77) as a reader:
>>> share_list(0, andrew, read_only=True)
Shared list ID 0 with andrew as reader
>>> set_user(andrew)
>>> get_list(0)
Access denied. User andrew is not authorized to Get List on [0]Andrew has the role (reader). The RBAC layer says yes. But
the ABAC guardrail compares an attribute of the principal
(location = XYZ77) with an attribute of the resource’s owner
(location = ABC17), they don’t match, Andrew isn’t a
job-level-7 person at a DEF* site—
24.6.3 Trade-offs
ABAC pros—
ABAC cons—
Setup cost: defining the attribute vocabulary, plumbing attribute sources (HR system, device posture, geo-IP), and authoring rules is a serious engineering effort—
much heavier than writing a role table. Error cost: a wrong ABAC rule is subtle. A wrong role assignment is “Bob is an Admin, oops”; a wrong attribute rule is “everyone whose department string is capitalized differently got locked out Saturday.” Getting it wrong at the outset is expensive to unwind.
Legibility: answering “who can currently access resource X?” now requires evaluating predicates over live data, not reading a table.
Common misconception: “ABAC is just RBAC with more features,
so it’s strictly better.” No—
24.7 RBAC vs. ABAC: Choosing
24.7.1 The comparison in one table
RBAC | ABAC | |
grants access by | roles (group membership) | attributes of user/resource/action/environment |
granularity | coarse -- per role | fine -- per predicate |
dynamic context | no | yes (time, location, device...) |
setup effort | low | high (attribute vocabulary + data plumbing) |
runtime cost | trivial checks | evaluate predicates over current data |
auditability | read the role table | evaluate policies against live attributes |
failure mode | role explosion | mis-specified rules, opaque behavior |
best-fit scale | small/simply-structured, stable duties | large, dispersed, context-sensitive |
24.7.2 Okta’s five scenarios (learn these as reflexes)
Small workgroup (a 15-person construction firm) → RBAC. Few people, few files, clear jobs. Anything fancier is over-engineering.
Geographically diverse workforce → ABAC. Rules like “access only during business hours in the branch’s own time zone” need environment attributes.
Time-defined access (sensitive systems locked outside office hours) → ABAC. Time is an environment attribute; RBAC has nowhere to put it.
Large but simply structured org (a medical practice: receptionists schedule, doctors chart, billing bills) → RBAC. Big ≠ complex. Access tracks job titles, so roles fit naturally.
Creative enterprises where access follows the document, not the job (this campaign’s drafts visible to everyone this week, three people next week) → ABAC. The deciding factors are resource attributes.
The pattern: does access depend only on who you are organizationally? RBAC. Does it depend on properties of the resource or the moment? ABAC.
24.7.3 The real answer: hybrid
Okta is blunt: most organizations use both. RBAC for the
coarse outer walls, ABAC for the fine-grained rules inside them.
Hide the sensitive servers from anyone without the Engineer
role (RBAC—
You’ve already seen a hybrid: TinyTodo. Reader/editor teams are
RBAC; the owner rule and the location guardrail are ABAC. What you
need now is a language where both styles coexist in one policy
set—
24.8 Policy-as-Code with Cedar
24.8.1 The architecture: separating decision from enforcement
Externalized authorization has a standard anatomy (the Permit.io
articles use this vocabulary—
+--------------------------------------------------+ |
| Application (e.g., FastAPI route / middleware) | |
| = ENFORCEMENT POINT (PEP) | |
| "may sofia ViewGrade grade_17?" | |
+---------------+------------------^---------------+ |
| request | Allow / Deny |
+---------------v------------------+---------------+ |
| Policy engine (Cedar) = DECISION POINT (PDP) | |
+-------^------------------------------^-----------+ |
| policies | entities/data |
+----------+---------+ +---------+----------+ |
| Policy store (git!)| | Entity data (users,| |
| *.cedar files | | teams, resources) | |
+--------------------+ +--------------------+ |
Figure 2: Enforcement asks, the engine decides, policies live in version control.
The enforcement point is thin: gather (principal, action, resource, context), ask, obey. It never contains rules.
The decision point evaluates policies against entity data. It never touches your business logic.
Policies live in git—
reviewed in PRs, validated in CI, versioned, revertible. Common Fate’s point: your team already has excellent governance for source code (review, approvals, history); authorization-as-code inherits all of it for free. They even ship a GitHub Action that validates Cedar policies in CI, flagging errors before deployment.
Change the rules → edit a .cedar file → merge. Zero application redeploys. The Permit.io OPAL tutorial demonstrates this end-to-end: a Node.js blog app and a Python Flask app share one policy store; adding “writers may auto-publish only above 1000 karma” was a one-file policy edit that instantly governed both apps.
24.8.2 What Cedar is
Cedar is an open-source policy language and evaluation engine, created at AWS by the automated-reasoning team, released in 2023, written in Rust (decisions in ~milliseconds), with a peer-reviewed formal model behind it. Three facts position it:
It’s general-purpose. Unlike AWS IAM policies (full of AWS-specific constructs like ARNs), Cedar has no cloud assumptions—
you define your own entity types (User, Team, List, Grade) and actions. It powers Amazon Verified Permissions (Cedar-as-a-managed-service) but runs equally well embedded in your own app. It’s purpose-built for application authorization. Where OPA’s Rego is a general-purpose query language you can use for authz, Cedar’s syntax is the authorization triple, verbatim: which principal may take which action on which resource.
It’s designed to be analyzable. The language is deliberately restricted (no loops, terminating by construction) so tools can prove things about policies—
e.g., that two policy sets are exactly equivalent, or validate every policy against a schema. Ecosystem pieces you’ll meet in the readings: Cedar-Agent (run the engine as an HTTP sidecar), OPAL (keep policies/data synced across a fleet of agents), Common Fate (just-in-time access built on Cedar).
24.8.3 Cedar syntax: effect, scope, conditions
Anatomy of a policy:
permit( // 1. EFFECT: permit or forbid
principal == User::"John", // 2. SCOPE: who...
action == Action::"view", // ...doing what...
resource // ...to what (bare = any)
)
when { // 3. CONDITIONS (optional)
resource in Folder::"John's Stuff" // when { ... } and/or
&& context.authenticated == true // unless { ... }
};1. Effect. permit grants; forbid revokes. There is no third option.
2. Scope. Always the triple (principal, action, resource). Each slot is either:
bare (principal)—
matches anything; == Type::"id"—
exactly this entity; in Type::"group"—
this entity or any (transitive) descendant of it in the hierarchy; for action only: in [Action::"a", Action::"b"]—
any of a listed set.
3. Conditions. when { ... } (must be true) and unless { ... } (must be false), with boolean operators, attribute access (principal.joblevel, resource.owner), string matching (like "DEF*"), set membership, and extension types (ip(...), decimal(...)).
Now the sentence that ties this lecture together—
The policy scope expresses an RBAC-style policy; the condition clauses refine it into ABAC.
principal in Role::"Editor" in the scope—
Entities are written Type::"id"—
24.8.4 Evaluation semantics: three rules, no ordering
Given a request (principal, action, resource, context) and a set of policies, Cedar evaluates every policy independently and combines:
If any forbid policy matches → Deny. Always. No permit can override a forbid.
Otherwise, if at least one permit matches → Allow.
Otherwise → Deny (default deny—
nothing matched, so no).
+- any forbid matches? --yes--> DENY |
request ----->| |
+- else: any permit matches? --yes--> ALLOW |
+--no--> DENY (default) |
Figure 3: Cedar’s decision procedure.
Consequences worth pausing on:
Policy order is irrelevant. Unlike firewall rules or IAM statement ordering headaches, shuffling a Cedar policy file cannot change any decision. Each policy is standalone.
forbid policies are guardrails. Because they’re un-overridable, they’re the natural home for organization-wide invariants: “interns never create lists,” “no grade changes after the semester closes,” “nothing from outside the corporate network.” Permits carve doors into a default-deny wall; forbids weld some doors shut permanently.
You never write “deny by default” yourself. It’s the engine’s floor.
Worked micro-example (from the Permit.io tutorial). Policies:
permit(principal in Role::"Viewer", action == Action::"get", resource);
forbid(principal in Role::"Viewer", action, resource == Document::"non_viewer.pdf");Request: may User::"John" (a Viewer) get
Document::"some_document.pdf"? Permit matches, no forbid
matches → Allow. Same John, same action,
Document::"non_viewer.pdf"? The permit still
matches—
24.8.5 Schemas: type-checking your policies
Policies are code; code has typos. Cedar’s schema declares your entity types (with their attributes) and actions (with which principal/resource types each applies to), and the validator checks every policy against it before deployment. From TinyTodo’s tinytodo.cedarschema:
entity List in [Application] = {
"editors": Team, "name": String, "owner": User,
"readers": Team, "tasks": Tasks,
};
entity User in [Team, Application] = { "joblevel": Long, "location": String, };
entity Team in [Team, Application];
action CreateList, GetLists appliesTo { principal: [User], resource: [Application] };
action GetList, UpdateList, DeleteList appliesTo { principal: [User], resource: [List] };Misspell readers as Readers in a policy, or reference
Action::"CrateTask", and validation fails at startup—
24.8.6 Two more features you’ll meet in the wild
Annotations: @id("admin-omnipotence") names a policy—
the name then shows up in decision diagnostics (“allowed because of admin-omnipotence”), which turns “why was this allowed?!” incidents from archaeology into a log line. Common Fate uses @advice("You cannot approve your own access request") annotations to surface human-readable explanations in their UI. Templates: a policy with holes—
permit(principal == ?principal, action == Action::"download", resource in ?resource)— instantiated per user/resource pair without duplicating policy text. This is how you avoid writing a thousand copies of “X may access folder Y.” (TinyTodo has a template-based variant; see TUTORIAL_TEMPLATE.md in the folder.)
A lovely real-world composition from the Common Fate
reading—
@advice("You cannot approve your own access request")
forbid (principal, action == Access::Action::"Approve", resource)
when { principal == resource.principal };That’s constrained RBAC’s “separation of duties” (Role-Based Access Control (RBAC)), implemented as a three-line ABAC guardrail. The models really do compose.
24.9 TinyTodo End to End
Time to cash in the running example. Everything in this section is
in rbac-abac/tinytodo/—
24.9.1 The four policies
The entire authorization model of the app—
// Policy 0: Any User can create a list and see what lists they own
permit (
principal,
action in [Action::"CreateList", Action::"GetLists"],
resource == Application::"TinyTodo"
);
// Policy 1: A User can perform any action on a List they own
permit (principal, action, resource is List)
when { resource.owner == principal };
// Policy 2: A User can see a List if they are either a reader or editor
permit (principal, action == Action::"GetList", resource)
when { principal in resource.readers || principal in resource.editors };
// Policy 3: A User can update a List and its tasks if they are an editor
permit (
principal,
action in [Action::"UpdateList", Action::"CreateTask",
Action::"UpdateTask", Action::"DeleteTask"],
resource
)
when { principal in resource.editors };Read them with Policy-as-Code with Cedar eyes: Policy 0 is pure scope
(RBAC-ish: everyone, two actions, one resource—
24.9.2 The enforcement point in the code
Every handler in the Rust server has the same first
line—
fn create_task(&mut self, r: CreateTask) -> Result<AppResponse> {
self.is_authorized(&r.uid, &*ACTION_CREATE_TASK, &r.list)?; // ask Cedar; bail on Deny
let list = self.entities.get_list_mut(&r.list)?; // only reached if allowed
let task_id = list.create_task(r.name);
Ok(AppResponse::TaskId(task_id))
}And is_authorized is a thin wrapper around the engine—
let response = self.authorizer.is_authorized(&q, &self.policies, &es);
match response.decision() {
Decision::Allow => Ok(()),
Decision::Deny => Err(Error::AuthDenied(response.diagnostics().clone())),
}Notice what is not here: not one if user.role == ... anywhere in application code. The handler doesn’t know the rules exist. That’s the decoupling from Policy-as-Code with Cedar, realized.
24.9.3 The trace: why kesha can’t create a task
Request: principal User::"kesha", action Action::"CreateTask", resource List::"0" (owner: andrew; readers: Team::"1" ⊇ interns; editors: Team::"2", empty). The engine evaluates all four policies:
Policy | Test | Result |
0 | is CreateTask in [CreateList, GetLists]? | false |
1 | is List::"0".owner (= andrew) == kesha? | false |
2 | is the action GetList? | false |
3 | CreateTask is in the list, but is kesha in List::"0".editors? kesha's parents: only Application::"TinyTodo" -- no path to Team::"2" | false |
No forbids exist; no permit satisfied; default deny. If
andrew had made the same request, Policy 1 alone would flip
it to Allow. And after share_list(0, interns,
read_only=True), aaron’s GetList is allowed by Policy
2—
24.9.4 Changing the rules without touching the app
The tutorial’s three extensions, each a pure policy-file edit—
Policy 4—
@id("admin-omnipotence")
permit (principal in Team::"admin", action, resource in Application::"TinyTodo");Emina (the one member of Team::"admin", per Figure 1) can now
read and delete anyone’s list—
Policy 5—
forbid (principal in Team::"interns",
action == Action::"CreateList",
resource == Application::"TinyTodo");Policy 0 permits everyone to create lists; this forbid carves interns back out. aaron’s create_list("my task list") → Access denied, even though a permit matches. Forbid wins; order irrelevant.
Policy 6—
One app, one policy file, and we’ve expressed flat RBAC,
hierarchical RBAC, separation-of-duties-style constraints,
ownership, and environment/attribute rules—
24.10 GitHub-Ready Mini-Project: terpgrades
TinyTodo’s engine-side is Rust; your projects in this course are
Python. Happily the folder also contains cedar-py
(cedarpy on PyPI)—
Spot the models before you read the code: instructor/TA/student is RBAC; “own section” and “own grade” are ABAC over resource attributes; the semester lock is an ABAC guardrail over context. Hybrid, like every real system.
24.10.1 Repository structure
terpgrades/ |
|-- README.md |
|-- requirements.txt |
|-- terpgrades/ |
| |-- __init__.py |
| |-- authz.py # the enforcement point (PEP): thin wrapper over cedarpy |
| |-- policies.cedar # the rules (PDP input) -- the interesting file |
| `-- entities.json # users, roles, grades as Cedar entities |
`-- tests/ |
`-- test_authz.py # pytest suite: every rule, allow AND deny cases |
24.10.2 requirements.txt
cedarpy>=4.1.0 |
pytest>=8.0 |
24.10.3 terpgrades/policies.cedar
// Policy 0 (RBAC): Instructors can perform any action on any resource.
@id("instructor-omnipotence")
permit (
principal in Role::"Instructor",
action,
resource
);
// Policy 1 (RBAC scope + ABAC condition): TAs may view and enter grades,
// but only for students in their own section.
@id("ta-own-section")
permit (
principal in Role::"TA",
action in [Action::"ViewGrade", Action::"SubmitGrade"],
resource
)
when {
principal has section && resource has section &&
principal.section == resource.section
};
// Policy 2 (ABAC relationship): a student may view their own grade.
@id("student-own-grade")
permit (
principal in Role::"Student",
action == Action::"ViewGrade",
resource
)
when { resource.student == principal };
// Policy 3 (ABAC guardrail over context): once the semester closes,
// NOBODY changes grades -- not even instructors. Forbid beats permit.
// The `has` guard is load-bearing -- see the last test below.
@id("semester-lock")
forbid (
principal,
action == Action::"ChangeGrade",
resource
)
unless { context has semester_open && context.semester_open == true };Four policies, every concept from the lecture: scope-only RBAC (0), scope+condition hybrid (1), attribute relationship (2), un-overridable context guardrail (3).
24.10.4 terpgrades/entities.json
Cedar’s JSON entity format: each entity has a uid, attrs, and parents (the membership DAG). Attribute values that are entity references are wrapped in __entity.
[
{ "uid": { "type": "Role", "id": "Instructor" }, "attrs": {}, "parents": [] },
{ "uid": { "type": "Role", "id": "TA" }, "attrs": {}, "parents": [] },
{ "uid": { "type": "Role", "id": "Student" }, "attrs": {}, "parents": [] },
{ "uid": { "type": "User", "id": "anwar" },
"attrs": {},
"parents": [ { "type": "Role", "id": "Instructor" } ] },
{ "uid": { "type": "User", "id": "tamara" },
"attrs": { "section": "0101" },
"parents": [ { "type": "Role", "id": "TA" } ] },
{ "uid": { "type": "User", "id": "sofia" },
"attrs": {},
"parents": [ { "type": "Role", "id": "Student" } ] },
{ "uid": { "type": "User", "id": "raj" },
"attrs": {},
"parents": [ { "type": "Role", "id": "Student" } ] },
{ "uid": { "type": "Grade", "id": "g-sofia-hw1" },
"attrs": {
"student": { "__entity": { "type": "User", "id": "sofia" } },
"section": "0101",
"assignment": "hw1"
},
"parents": [] },
{ "uid": { "type": "Grade", "id": "g-raj-hw1" },
"attrs": {
"student": { "__entity": { "type": "User", "id": "raj" } },
"section": "0202",
"assignment": "hw1"
},
"parents": [] }
]Note tamara TAs section 0101; sofia’s grade is in 0101, raj’s in 0202. Those two facts drive half the test suite.
24.10.5 terpgrades/authz.py
"""The enforcement point: gather the request, ask Cedar, return the decision.
No rules live in this file -- that's the whole point. Rules are in
policies.cedar; this module only asks questions and relays answers.
"""
import json
from pathlib import Path
from cedarpy import is_authorized
_BASE = Path(__file__).parent
_POLICIES = (_BASE / "policies.cedar").read_text()
_ENTITIES = json.loads((_BASE / "entities.json").read_text())
def check(principal: str, action: str, resource: str, context: dict | None = None) -> bool:
"""May `principal` perform `action` on `resource` under `context`?
Args use Cedar UID syntax, e.g. check('User::"sofia"',
'Action::"ViewGrade"', 'Grade::"g-sofia-hw1"').
"""
request = {
"principal": principal,
"action": action,
"resource": resource,
"context": context or {},
}
result = is_authorized(request, _POLICIES, _ENTITIES)
return result.allowed
def explain(principal: str, action: str, resource: str, context: dict | None = None):
"""Return the full AuthzResult (decision + diagnostics listing the policies that fired)."""
request = {
"principal": principal,
"action": action,
"resource": resource,
"context": context or {},
}
return is_authorized(request, _POLICIES, _ENTITIES)24.10.6 tests/test_authz.py
Testing-lecture discipline applies: for every rule, test the allow and the deny. An authorization test suite that only checks allows is checking the doors open, never that they lock.
from terpgrades.authz import check
SEMESTER_OPEN = {"semester_open": True}
SEMESTER_CLOSED = {"semester_open": False}
# --- Policy 0: instructor RBAC ------------------------------------------------
def test_instructor_can_view_any_grade():
assert check('User::"anwar"', 'Action::"ViewGrade"', 'Grade::"g-raj-hw1"')
def test_instructor_can_change_grades_while_semester_open():
assert check('User::"anwar"', 'Action::"ChangeGrade"',
'Grade::"g-sofia-hw1"', SEMESTER_OPEN)
# --- Policy 1: TA scoped to own section (RBAC + ABAC) -------------------------
def test_ta_can_grade_own_section():
assert check('User::"tamara"', 'Action::"SubmitGrade"', 'Grade::"g-sofia-hw1"')
def test_ta_cannot_grade_other_section():
assert not check('User::"tamara"', 'Action::"SubmitGrade"', 'Grade::"g-raj-hw1"')
def test_ta_cannot_change_grades_at_all():
# ChangeGrade isn't in the TA policy's action list -- default deny.
assert not check('User::"tamara"', 'Action::"ChangeGrade"',
'Grade::"g-sofia-hw1"', SEMESTER_OPEN)
# --- Policy 2: students see only their own grade (ABAC relationship) ----------
def test_student_can_view_own_grade():
assert check('User::"sofia"', 'Action::"ViewGrade"', 'Grade::"g-sofia-hw1"')
def test_student_cannot_view_someone_elses_grade():
assert not check('User::"sofia"', 'Action::"ViewGrade"', 'Grade::"g-raj-hw1"')
def test_student_cannot_submit_grades():
assert not check('User::"raj"', 'Action::"SubmitGrade"', 'Grade::"g-raj-hw1"')
# --- Policy 3: the semester lock (forbid overrides permit) --------------------
def test_semester_lock_beats_even_the_instructor():
assert not check('User::"anwar"', 'Action::"ChangeGrade"',
'Grade::"g-sofia-hw1"', SEMESTER_CLOSED)
def test_semester_lock_with_missing_context_denies():
# No context key -> the `has` guard makes `unless` false -> forbid applies.
assert not check('User::"anwar"', 'Action::"ChangeGrade"', 'Grade::"g-sofia-hw1"')The last test is the subtlest and the most important—
24.10.7 Run it
pip install -r requirements.txt
python -m pytest -vExpected output: 10 tests, all passing—
tests/test_authz.py::test_instructor_can_view_any_grade PASSED |
tests/test_authz.py::test_instructor_can_change_grades_while_semester_open PASSED |
tests/test_authz.py::test_ta_can_grade_own_section PASSED |
tests/test_authz.py::test_ta_cannot_grade_other_section PASSED |
tests/test_authz.py::test_ta_cannot_change_grades_at_all PASSED |
tests/test_authz.py::test_student_can_view_own_grade PASSED |
tests/test_authz.py::test_student_cannot_view_someone_elses_grade PASSED |
tests/test_authz.py::test_student_cannot_submit_grades PASSED |
tests/test_authz.py::test_semester_lock_beats_even_the_instructor PASSED |
tests/test_authz.py::test_semester_lock_with_missing_context_denies PASSED |
10 passed in 0.01s |
And interactively:
>>> from terpgrades.authz import check, explain
>>> check('User::"tamara"', 'Action::"SubmitGrade"', 'Grade::"g-raj-hw1"')
False
>>> explain('User::"anwar"', 'Action::"ViewGrade"', 'Grade::"g-raj-hw1"').diagnosticsTo change the rules, edit terpgrades/policies.cedar—
24.10.8 Design decisions worth internalizing
authz.py contains zero rules. If you find yourself writing if "TA" in ... in Python, stop—
that rule belongs in policies.cedar, where it’s testable in isolation and changeable without redeploying. Entity references in attrs use __entity—
that’s how Policy 2’s resource.student == principal compares entities rather than strings. Comparing "sofia" == "sofia " (trailing space) silently fails; comparing typed entity UIDs cannot. The has checks (Policies 1 and 3) make the policies total. A missing attribute is an evaluation error, and an erroring policy is skipped. For a permit (Policy 1), skipped means denied—
inconvenient but safe. For a forbid (Policy 3), skipped means the guardrail disappears— catastrophic. Guard every attribute access; defensive policy-writing mirrors defensive programming.
24.11 Practice Exercises
24.11.1 Basic
E1. Classify each as authentication or authorization: (a) checking a password hash; (b) verifying an MFA code; (c) deciding whether a user may delete a repository; (d) rejecting an expired session token; (e) hiding the “Admin” tab from non-admins. (One of these is a trick—
which UI practice is not real access control, and which OWASP category does relying on it fall under?) E2. For each scenario, choose RBAC, ABAC, or hybrid, and justify in one sentence: (a) a 12-person bakery’s scheduling app; (b) a hospital system where lab results are visible only to the treating physician, during their shift; (c) a university LMS with students/TAs/instructors; (d) a defense contractor where document access depends on clearance level and project assignment and being on-site.
E3. In Figure 1, list every team that User::"aaron" is in (remember transitivity, and remember what in does with the entity itself). Is User::"kesha" in Team::"temp"?
E4. Without running anything, give Cedar’s decision for each, under TinyTodo policies 0–3 only, where list 0 is owned by andrew with interns as readers: (a) andrew DeleteList list 0; (b) aaron GetList list 0; (c) aaron DeleteTask list 0; (d) emina GetList list 0.
E5. State Cedar’s three-step decision procedure from memory, and explain why policy order can never matter.
24.11.2 Intermediate
E6. Write a Cedar policy: members of Team::"staff" may perform Action::"View" on any resource, but only when context.mfa == true. Label which part of your policy is RBAC and which is ABAC.
E7. Your company has 6 departments, 4 offices, and 3 seniority tiers, and access rules depend on all three. Compute the role count for a pure-RBAC encoding, then rewrite the design with ABAC in at most 3 policies (sketch, not exact syntax). What did each design cost you?
E8. In terpgrades, add a Grader role that may SubmitGrade in any section but may never ViewGrade. Write the policy, then write the two pytest cases (one allow, one deny) that pin it down.
E9. TinyTodo Policy 6 denied Andrew a list that was explicitly shared with him. A teammate calls this a bug: “the share should win—
the owner chose to share it.” Write a 3–4 sentence reply explaining why guardrail semantics are a feature, and name one real-world regulation-driven rule with the same shape. E10. The terpgrades semester lock reads context.semester_open supplied by the caller. What’s the trust problem with that, and where should that fact actually come from? (Hint: recall which layer supplies context in the Verified Access example from the Cedar reading, and think about what “never trust the client” means when your enforcement point is the server.)
24.11.3 Advanced
E11. Role explosion, quantified. With U users, R roles, and P permissions, compare the number of stored assignments in (a) direct user→permission grants, (b) RBAC, assuming each user averages 2 roles and each role averages P/R permissions. Now add a new compliance rule that cuts across roles (e.g., “nobody outside the EU touches EU-resident data”). Show what each design must change, and what a single ABAC forbid changes instead. What’s the general principle about cross-cutting rules?
E12. Entity slicing. TinyTodo ships all entities to the engine on every request. Design the minimal entity set needed to correctly decide “may kesha CreateTask on list 0” under policies 0–3, and justify each inclusion. Then show how the tutorial’s Policy 7 (resource.owner in Team::"interns") breaks your slice, and propose how a slicing algorithm could stay correct as policies evolve.
E13. Design an authorization model for this course’s TerpTasks app (from the FastAPI lecture): users own task lists; lists can be shared read-only or read-write; a staff team can moderate anything; deletions are forbidden outside 9am–5pm College Park time. Deliver: the entity types with attributes/parents, the full Cedar policy set with @id annotations, and the deny-side test matrix (principal × action × expected-deny) you’d hand to pytest.
24.12 Summary
24.12.1 Key takeaways
Authentication is who you are; authorization is what you may do. Both live inside IAM. The login is not the lock—
and Broken Access Control is OWASP’s #1 for a reason. RBAC: permissions → roles → users. Simple, fast, auditable, perfect for org-chart-shaped access—
until granularity demands breed role explosion. ABAC: decisions from attributes of principal, resource, action, and environment. Fine-grained and dynamic—
at the price of setup effort, expertise, and legibility. Most real systems are hybrids: RBAC for the outer walls, ABAC for the fine structure inside. Choose per rule, not per system.
Policy-as-code moves rules out of application code into a reviewed, versioned, testable policy store; the app becomes a thin enforcement point asking a decision point. Rules change without redeploys.
Cedar is an open-source policy language + engine built for exactly this: scope expresses RBAC, conditions express ABAC, and the semantics are three lines—
forbid beats permit; some permit must match; otherwise default deny— with policy order irrelevant, schemas to validate against, and one sharp edge: a policy that errors (e.g., on a missing attribute) is skipped, so guard attribute access with has, especially in forbids. TinyTodo showed the whole stack: entity hierarchy (DAG + transitive in), thin handlers calling is_authorized, four policies covering ownership, roles, and attribute guardrails—
and three rule changes made without touching application code.
24.12.2 Terminology
Term | Meaning |
IAM | the umbrella discipline: identity lifecycle + access management |
principal/action/resource/context | the universal authorization quadruple |
least privilege | grant the minimum access needed |
default deny | no matching rule => denied |
DAC / MAC | owner-discretion / central-mandate access control |
RBAC | permissions attach to roles; users get roles |
separation of duties | constraints preventing one person holding conflicting roles |
role explosion | RBAC's failure mode: roles multiply to fake granularity |
ABAC | decisions computed from attributes via if/then policies |
policy-as-code | rules as declarative, versioned artifacts, not inline code |
PEP / PDP | enforcement point (asks & obeys) / decision point (evaluates) |
Cedar | open-source policy language + evaluation engine (AWS, 2023) |
entity, UID, parents | Cedar's typed objects, Type::"id", and membership DAG |
in | transitive reachability in the hierarchy (includes self) |
permit / forbid | grant / un-overridable revoke |
schema & validation | type-checking policies before deployment |
policy template | a policy with ?principal/?resource holes, instantiated per link |
24.12.3 Common mistakes
Checking authentication and calling it authorization (“they’re logged in, so serve the object”)—
that’s an IDOR, the classic Broken Access Control bug. Hiding UI instead of denying on the server. The button being invisible is not a security control; the API is the perimeter.
Granting one-off direct permissions inside an RBAC system—
breaks NIST rule 3 and forks your model. Fighting granularity with more roles instead of recognizing the attributes screaming to get out.
Writing only allow-side tests. Test the denies; the denies are the product.
Unguarded attribute access in a forbid. A missing attribute errors the policy, an erroring policy is skipped, and a skipped forbid is a guardrail that silently failed open. Always write x has attr && x.attr == ..., and let schema validation catch the rest.
Putting membership checks in when clauses that belong in the scope—
legibility and performance both suffer.
24.12.4 Connections
Backward: terpgrades.check() is one dependency/middleware away from guarding every TerpTasks route—
the PEP slots exactly where auth middleware went in the Layered Architecture lecture; policy sets are code, so the testing lecture’s deny-matrix suite is the spec; and Broken Access Control from the OWASP notes is what all of this prevents. Forward: AI agents are principals too. An agent with your credentials needs scoped authority—
time-boxed, attribute-limited, guard-railed. The Common Fate reading’s just-in-time access model (request → approve → time-bound grant, all in Cedar) is precisely the shape of the “how do we let the agent act, but not too much” problem, and every vendor in your readings is now racing to apply it to non-human identities. And when you wire tools to a model over MCP, each tool call is an authorization request wearing a trench coat. Same quadruple. Same answer: policy, not vibes.