Lesson 33 of 59Identity and access
Authorization: Roles, Permissions and Ownership
Model who may do what with RBAC, attribute rules and relationships, wire the checks into FastAPI at the right layers, and prove them with a permission matrix test.
You join a team building invoicing software for small companies. The first ticket says: "Approvers can approve invoices, but not their own, and only up to their limit." The second: "Contractors should only see the projects they were invited to." The third is a bug report from a customer whose accountant could see another company's invoices. None of these is about logging in. They are all authorization, and the code that answers them tends to grow by accident: an if user.role == "admin" here, a forgotten filter there. This lesson gives you the models to pick from and a structure that keeps the checks in one place and testable.
Where authorization lives
Authentication decides who is calling; authorization decides what they may do, as you saw in Authentication and JWTs. The OWASP API list puts broken object level authorization (BOLA) at number one, and the API Security lesson showed the core fix: scope queries by owner. This lesson builds the rest of the system around that idea.
Every authorization decision answers one question: may this subject perform this action on this resource, in this context? Your code asks it at three layers, and each catches something the others cannot:
- Route level: "may this user call
POST /invoices/{id}/approveat all?" This needs only the user and the action. It is cheap, and it runs before any database work. - Resource level: "may this user approve invoice 812?" This needs the loaded object: who created it, its status, its amount. It belongs in the service layer, right after loading.
- Query level: "which invoices may this user see?" A list endpoint cannot check rows one by one after loading a million of them. The rule must become a
WHEREclause.
Most real bugs are a missing layer 2 or 3: the route checked a permission, then loaded any object by id.
RBAC: roles are bundles of permissions
Role-based access control (RBAC) gives users roles, and roles grant permissions. The important design choice is that your code checks permissions, never role names.
Press Run (⌘ Enter) to see what happens.Lin has two roles, and her permissions are the union of both. Now picture the code. if "approver" in user.roles breaks the day the business creates a "finance lead" role that may also approve. You hunt through the codebase for every role check. if "invoice:approve" in user.permissions keeps working: you grant the permission to the new role in data, and no code changes. Name permissions resource:action so they read clearly in code and in audit logs.
In a multi-company product, roles are usually per organisation: Ada is an admin in her own company and a viewer in a client's. Put org_id on user_roles and load the permissions for the organisation in the current request.
RBAC's failure mode is role explosion. Every exception becomes a new role: "approver-EU", "approver-under-10k", "approver-EU-under-10k-no-weekends". When roles start encoding facts about the resource or the situation, you need attributes, not more roles.
ABAC: rules about attributes
Attribute-based access control (ABAC) decides using attributes of the subject (department, approval limit), the resource (owner, status, amount, organisation), the action, and the environment (time, network). The approver ticket is a perfect example. Write each rule as a pure function: data in, boolean out, no database calls inside. Pure functions are trivial to unit test and easy to read in code review.
Press Run (⌘ Enter) to see what happens.Notice that the rules still start from an RBAC permission. In practice the two combine: roles say what kind of thing you may do, attributes narrow it to which objects and when. Also notice the organisation check comes first in every rule. Passing now in, rather than calling datetime.now() inside, keeps the function pure and the weekend rule testable.
Using the classes and rules above, what does this print? (24 October 2026 is a Saturday.)
sam = Subject(2, org_id=10, permissions=frozenset({"invoice:approve", "invoice:edit"}), approval_limit=5_000)
own = Invoice(900, org_id=10, created_by=2, status="submitted", amount=300)
print(can_edit(sam, own), can_approve(sam, own, datetime(2026, 10, 24, 9, 0)))ReBAC: relationships and inheritance
Some rules are about relationships: "Lin can see this document because it is in a folder shared with her team." Google Docs, GitHub and Notion work like this. Expressing it with roles or attributes gets painful fast, because access flows through chains: user to group, group to folder, folder to document.
Relationship-based access control (ReBAC) stores facts as tuples, (object, relation, subject), and answers checks by following them. The model comes from Google's Zanzibar paper (2019), which describes the system behind Drive, YouTube and Calendar sharing. Open-source and hosted systems in that style include OpenFGA, SpiceDB and Permit.io.
Press Run (⌘ Enter) to see what happens.The check: is user:lin a viewer of doc:roadmap? No tuple says so directly, and she is not an editor.
You need ReBAC when users share things with each other, when access inherits through hierarchies (organisation, workspace, project, file), or when you keep writing recursive queries to answer "can she see this?". A dedicated service then pays off: it answers checks in milliseconds at scale, and can list "everything Lin can see" for a search page. The costs are real too: another critical service to run, and keeping its tuples in sync with your database (write both in the same workflow, and reconcile). If your app has organisations and a few roles, you do not need it.
Match each requirement to the model that fits it most naturally.
Wiring it into FastAPI
Route-level checks fit a dependency factory: a function that takes the permission name and returns a dependency. It reads like a declaration on each route, and the check runs before any database work.
from typing import Annotated
from fastapi import Depends, HTTPException, status
from app.auth.deps import CurrentUser
from app.models import User
def require_permission(permission: str):
def checker(user: CurrentUser) -> User:
if permission not in user.permissions:
raise HTTPException(status.HTTP_403_FORBIDDEN, "Missing permission")
return user
return checker
Approver = Annotated[User, Depends(require_permission("invoice:approve"))]Resource-level checks run in the service layer, right after loading, so every caller (the route, a background job, a CLI command) gets the same rule:
from app.domain.errors import NotFound, PermissionDenied
from app.policies.invoices import can_approve
def approve_invoice(db: Session, user: User, invoice_id: int, now: datetime) -> Invoice:
invoice = db.scalars(
select(Invoice).where(Invoice.id == invoice_id, Invoice.org_id == user.org_id)
).first()
if invoice is None:
raise NotFound("invoice") # also covers other orgs' invoices
if not can_approve(user, invoice, now):
raise PermissionDenied("invoice:approve")
invoice.status = "approved"
invoice.approved_by = user.id
return invoiceThe route stays thin: def approve(invoice_id: int, user: Approver, db: DB) calls the service, and an exception handler maps NotFound to 404 and PermissionDenied to 403.
List endpoints need the rule as a query filter, because filtering after loading leaks counts, breaks pagination and is slow. Give each model a helper such as visible_invoices(user) that returns select(Invoice).where(Invoice.org_id == user.org_id) plus any extra rule (contractors: Invoice.project_id.in_(user.project_ids)), and have every list and search endpoint start from it. A list endpoint built from a bare select(Invoice) should fail code review.
Policy engines and centralised authorization
As rules multiply across services, some teams move them out of application code into a policy engine:
- OPA (Open Policy Agent) with its Rego language: general purpose, popular for infrastructure (Kubernetes admission, Terraform checks) as well as APIs. Your service sends a JSON input and gets a decision.
- Cedar: a policy language from AWS, open source, and the engine behind Amazon Verified Permissions. Designed to be fast and analysable, so tools can prove things about your policies.
- Oso, and the ReBAC services above, which include their own modelling languages.
The trade-off: centralised policies give one place to read, audit and change rules, consistent decisions across services written in different languages, and policy changes without redeploying. They also add latency, a network dependency on the authorization path, and a second language your team must know. The hardest part is usually data: the engine needs the invoice's status and owner to decide, so either your service sends it in every request or the engine keeps a copy. For a single FastAPI service, pure Python policy functions with tests are usually the better choice. Reach for an engine when several services must enforce the same rules.
403 or 404, audit logs, and impersonation
403 or 404? If the caller may not know the resource exists, answer 404, exactly as for a missing one. That covers another organisation's invoices. If they can see it but not perform this action (Sam viewing an invoice he is not allowed to approve), answer 403 with a clear reason. Be consistent, and make sure the 404 for "exists elsewhere" is byte-for-byte the same as for "never existed", including timing where it matters.
Audit logs. Record denials (a spike of 403s or 404s from one account is someone probing ids) and every privileged action: role changes, approvals, exports, deletions. Each entry needs who, what, which resource, when, the outcome, and the request id. Write audit events to an append-only store that the people being audited cannot edit.
Impersonation. Support teams want to "log in as" a customer to reproduce bugs. Treat it as a privileged feature: a separate permission, a reason field, a time limit, a banner in the UI, and an audit trail that records both identities on every action (actor=support:41, acting_as=user:7). Block the most dangerous actions while impersonating, such as changing passwords, payment details or exporting data. This is least privilege applied to your own staff, and it is a common finding in security reviews and compliance audits.
Testing with a permission matrix
Authorization bugs are rarely in the code you tested; they are in the endpoint nobody tested as the wrong user. A permission matrix test lists roles, endpoints and expected status codes in one table, so missing rows are visible in review:
import pytest
MATRIX = [
("viewer", "GET", "/invoices/812", 200),
("viewer", "POST", "/invoices/812/approve", 403),
("clerk", "POST", "/invoices/812/approve", 403),
("approver", "POST", "/invoices/812/approve", 200),
("admin", "POST", "/invoices/812/approve", 200),
("outsider", "GET", "/invoices/812", 404), # admin of another org
("outsider", "POST", "/invoices/812/approve", 404),
]
@pytest.mark.parametrize(("role", "method", "path", "expected"), MATRIX)
def test_permission_matrix(client_as, role, method, path, expected):
client = client_as(role) # fixture: overrides get_current_user
response = client.request(method, path)
assert response.status_code == expectedNote the "outsider" rows: an admin from another organisation must get 404 everywhere. Add a test that walks the app's routes and fails if any route is missing from the matrix, so a new endpoint cannot ship untested. Keep the pure policy functions under plain unit tests too: they are fast, and they cover edge cases (weekends, limits, statuses) without HTTP.
Order the checks for POST /invoices/812/approve.
- Tap the steps below in the right order.
- RBAC
- Role-based access control: users get roles, roles grant permissions, and code checks the permissions.
- ABAC
- Attribute-based access control: decisions from attributes of the subject, resource, action and environment.
- ReBAC
- Relationship-based access control: access follows stored relationships, such as group membership and folder parents.
- role explosion
- RBAC breaking down into many near-duplicate roles because roles are used to encode resource or situation rules.
- policy engine
- A separate component (OPA, Cedar, Oso) that evaluates authorization rules written in its own policy language.
- permission matrix
- A table of roles, endpoints and expected status codes, run as parametrised tests.
- default deny
- Rules refuse access unless something explicitly grants it, so unforeseen cases fail closed.