Skip to content

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.

20 min read0/4 questions

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:

  1. Route level: "may this user call POST /invoices/{id}/approve at all?" This needs only the user and the action. It is cheap, and it runs before any database work.
  2. 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.
  3. 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 WHERE clause.

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.

Pythonrbac.py
import sqlite3 db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);CREATE TABLE roles (id INTEGER PRIMARY KEY, name TEXT UNIQUE);CREATE TABLE permissions (id INTEGER PRIMARY KEY, name TEXT UNIQUE);CREATE TABLE role_permissions (role_id INT REFERENCES roles, permission_id INT REFERENCES permissions, PRIMARY KEY (role_id, permission_id));CREATE TABLE user_roles (user_id INT REFERENCES users, role_id INT REFERENCES roles, PRIMARY KEY (user_id, role_id)); INSERT INTO users VALUES (1, 'ada'), (2, 'sam'), (3, 'lin');INSERT INTO roles VALUES (1, 'clerk'), (2, 'approver'), (3, 'auditor');INSERT INTO permissions VALUES (1, 'invoice:read'), (2, 'invoice:edit'), (3, 'invoice:approve'), (4, 'report:export');INSERT INTO role_permissions VALUES (1, 1), (1, 2), (2, 1), (2, 3), (3, 1), (3, 4);INSERT INTO user_roles VALUES (1, 1), (2, 2), (3, 1), (3, 3);""") def permissions_for(user_id: int) -> set[str]: rows = db.execute(""" SELECT DISTINCT p.name FROM user_roles ur JOIN role_permissions rp ON rp.role_id = ur.role_id JOIN permissions p ON p.id = rp.permission_id WHERE ur.user_id = ? """, (user_id,)) return {name for (name,) in rows} for user_id, name in db.execute("SELECT id, name FROM users"): print(f"{name:4}", sorted(permissions_for(user_id))) def can(user_id: int, permission: str) -> bool: return permission in permissions_for(user_id) print("lin can export:", can(3, "report:export"), "| ada can approve:", can(1, "invoice:approve"))
Output
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.

Quick check
Which check ages best as the business adds new roles?
Need a nudge? A hint rules out a wrong answer.

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.

Pythonpolicies.py
from dataclasses import dataclassfrom datetime import datetime @dataclass(frozen=True)class Subject: id: int org_id: int permissions: frozenset[str] approval_limit: int = 0 @dataclass(frozen=True)class Invoice: id: int org_id: int created_by: int status: str amount: int def can_edit(user: Subject, invoice: Invoice) -> bool: return ( invoice.org_id == user.org_id and "invoice:edit" in user.permissions and invoice.created_by == user.id and invoice.status == "draft" ) def can_approve(user: Subject, invoice: Invoice, now: datetime) -> bool: return ( invoice.org_id == user.org_id and "invoice:approve" in user.permissions and invoice.created_by != user.id # four-eyes rule and invoice.status == "submitted" and invoice.amount <= user.approval_limit and now.weekday() < 5 # no approvals at weekends ) ada = Subject(1, org_id=10, permissions=frozenset({"invoice:edit"}))sam = Subject(2, org_id=10, permissions=frozenset({"invoice:approve"}), approval_limit=5_000)draft = Invoice(812, org_id=10, created_by=1, status="draft", amount=1_200)submitted = Invoice(812, org_id=10, created_by=1, status="submitted", amount=1_200)tuesday = datetime(2026, 10, 20, 10, 0) print("ada edits her draft: ", can_edit(ada, draft))print("ada edits after submit: ", can_edit(ada, submitted))print("sam approves on Tuesday: ", can_approve(sam, submitted, tuesday))print("sam approves 9,000: ", can_approve(sam, Invoice(813, 10, 1, "submitted", 9_000), tuesday))
Output
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.

Predict the outputPython

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)))
Need a nudge? Hints walk you through it.

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.

Pythonrebac.py
# Relationship tuples: (object, relation, subject)TUPLES = { ("folder:plans", "owner", "user:ada"), ("folder:plans", "viewer", "group:eng#member"), # everyone in eng ("group:eng", "member", "user:lin"), ("doc:roadmap", "parent", "folder:plans"), ("doc:roadmap", "editor", "user:sam"),} # Rules: which relations imply which (an owner is an editor, an editor is a viewer)IMPLIED_BY = {"viewer": ["editor"], "editor": ["owner"]} def check(subject: str, relation: str, obj: str, depth: int = 0) -> bool: if depth > 10: # guard against cycles return False for o, r, s in TUPLES: if o != obj or r != relation: continue if s == subject: return True # direct grant if "#" in s: # a userset like group:eng#member group, group_rel = s.split("#") if check(subject, group_rel, group, depth + 1): return True for stronger in IMPLIED_BY.get(relation, []): if check(subject, stronger, obj, depth + 1): return True for o, r, parent in TUPLES: # inherit from the parent folder if o == obj and r == "parent" and check(subject, relation, parent, depth + 1): return True return False for who in ["user:ada", "user:sam", "user:lin", "user:kim"]: print(f"{who:9} view={check(who, 'viewer', 'doc:roadmap')!s:5} edit={check(who, 'editor', 'doc:roadmap')}")
Output
Press Run (⌘ Enter) to see what happens.
Why Lin can view doc:roadmap
user:lingroup:engfolder:plansdoc:roadmapuser:adauser:sammemberviewerparent ofownereditor

currentwaitingdone

The check: is user:lin a viewer of doc:roadmap? No tuple says so directly, and she is not an editor.

1/4

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 the pairs0/5 matched

Match each requirement to the model that fits it most naturally.

Choose an item, then its match on the other side.

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.

app/auth/permissions.py
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:

app/services/invoices.py
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 invoice

The 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:

tests/test_permissions.py
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 == expected

Note 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.

Put it in order5 steps

Order the checks for POST /invoices/812/approve.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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.