Notes
All notes

Authorization Methods (API Design #6)

A summer intern on the finance team calls POST /refunds with amount: 50000 — and it works. Authentication did its job: the API knew exactly who she was. The failure was that nothing ever asked the second question: is this person allowed to do this thing to this object right now?

That second question is authorization, and this chapter covers the six models you’ll meet on the roadmap — RBAC, ABAC, ReBAC, MAC, DAC, and PBAC — plus OAuth scopes, the coarse authorization every API consumer already touches. Each model is a different way to structure the same decision function.

By the end you will be able to pick a model for a real system, implement the check in a dozen lines, and explain why “check the role in the handler” stops scaling somewhere around your fifth role.

The decision, made precise

Every authorization system, whatever its acronym, evaluates some version of

\[ \text{allow} = f(\text{subject}, \text{action}, \text{resource}, \text{context}) \]

— user 77, refund.create, order 42, at 02:00 from an unknown IP. The models differ in where the rule lives: attached to the subject (roles), attached to the resource (ACLs), derived from attributes (ABAC), derived from relationships (ReBAC), or written as standalone policy (PBAC).

Two architectural habits matter more than the model. First, default deny: the absence of a rule means no, and rules only ever grant. Second, a policy decision point: one function or service answers f(...) for the whole API, so the rule lives in one auditable place instead of being smeared across forty handlers.

RBAC: roles as the unit

Role-Based Access Control assigns permissions to roles and roles to users. Nobody has permissions directly; they have support_lead, and support_lead has refund.create up to $500.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.3cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (u1) at (0,0) {intern};
  \node[b, fill=blue!10] (u2) at (0,-1.1) {Priya};
  \node[b, fill=orange!16] (r1) at (3.4,-0.1) {support\_agent};
  \node[b, fill=orange!16] (r2) at (3.4,-1.3) {support\_lead};
  \node[b, fill=green!10] (p1) at (7.2,0.2) {ticket.reply};
  \node[b, fill=green!10] (p2) at (7.2,-0.8) {refund.create $\le$ \$500};
  \node[b, fill=green!10] (p3) at (7.2,-1.8) {refund.create $\le$ \$5000};
  \draw[a] (u1) -- (r1); \draw[a] (u2) -- (r2);
  \draw[a] (r1) -- (p1); \draw[a] (r2) -- (p1); \draw[a] (r2) -- (p2);
  \draw[a, dashed] (r2.east) to[bend left=25] (p3.east);
\end{tikzpicture}

The implementation is a join:

PERMISSIONS = {
    "support_agent": {"ticket.reply"},
    "support_lead":  {"ticket.reply", "refund.create:500"},
}

def allowed(user, permission: str) -> bool:
    return any(permission in PERMISSIONS.get(role, ()) for role in user.roles)

allowed(intern, "refund.create:500")   # False — default deny
allowed(priya,  "refund.create:500")   # True

RBAC’s strength is auditability — “who can refund?” is one query. Its failure mode is role explosion: the moment limits vary (\(500 for leads, \)5000 for managers, $50k for finance, except on weekends, except for VIP customers), you either mint hundreds of micro-roles or you bolt conditions onto roles — and conditions are attributes, which means you’ve started building ABAC.

ABAC: attributes as the unit

Attribute-Based Access Control evaluates rules over attributes of the subject, resource, and context — no roles required:

def can_refund(user, order, ctx) -> bool:
    return (
        user.department == "finance"
        and order.amount <= user.refund_limit       # subject attribute
        and order.status == "paid"                  # resource attribute
        and ctx.hour in range(6, 22)                # context attribute
        and (user.region == order.region or user.region == "global")
    )

The rule reads like the business speaks: “finance staff may refund paid orders up to their personal limit, during business hours, in their region.” No new roles when limits change — limits are data on the user, not a schema change. ABAC handles exactly the conditions that exploded your RBAC, at the cost of a harder audit question: “who can refund?” is no longer a join but an evaluation of the policy against every user. Mature ABAC systems (OPA/Rego, Cedar) give you a policy language, a decision log, and tooling to answer that question.

ReBAC: relationships as the unit

Some permissions are not about what you are but how you’re connected: you may edit a document because you own it, comment because a teammate shared it with you, view because you’re in the folder’s org. Relationship-Based Access Control stores these as a graph and answers queries over paths:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.1cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (u) at (0,0) {Ada};
  \node[b, fill=orange!16] (t) at (3,0) {team eng};
  \node[b, fill=green!10] (f) at (6,0) {folder q3};
  \node[b, fill=gray!12] (d) at (9,0) {doc 7};
  \draw[a] (u) -- node[above, font=\rmfamily\scriptsize] {member} (t);
  \draw[a] (t) -- node[above, font=\rmfamily\scriptsize] {editor} (f);
  \draw[a] (f) -- node[above, font=\rmfamily\scriptsize] {parent} (d);
\end{tikzpicture}

can(ada, edit, doc7) is true because a path exists: member → editor → parent. This is Google Drive’s model, published as Zanzibar, and it’s the right fit whenever “sharing” is a first-class feature — the permission is a relationship, so model it as one. The cost is infrastructure: relationship tuples, graph queries, and consistency guarantees that a role table never demanded.

MAC, DAC, PBAC: the other three letters

The policy decision point in practice

Whichever model you choose, wire it as one function every request passes through — never as per-handler folklore:

@app.middleware("http")
async def authorize(request: Request, call_next):
    user = request.state.user                     # set by authn middleware (Ch. 5)
    resource = await load_resource(request)       # the object being touched
    decision = policy.evaluate(
        subject=user, action=f"{request.method} {request.url.path}",
        resource=resource, context={"ip": request.client.host, "hour": now().hour},
    )
    if not decision.allow:
        return problem_json(404 if decision.hide else 403)   # Ch. 9: don't leak existence
    return await call_next(request)

The win is a single seam: policy changes ship in one place, every decision can be logged (audit, Chapter 13), and “what can user 77 do?” becomes a question you can ask the policy engine instead of grep the codebase for. Mature setups externalize the function entirely — OPA or Cedar as a sidecar — so policy is data, versioned and reviewed like code (that’s PBAC, below).

Scopes: coarse authorization at the edge

OAuth scopes (Chapter 5) are authorization too — the coarsest layer. A token carrying read:invoices may list invoices but never create refunds, no matter how senior its owner is. Think of the stack as three nested gates: the scope gates what the client app may do, the user’s authorization gates what the person may do, and the effective permission is the intersection. A read-only token wielded by an admin still cannot write.

Choosing a model

Need Fit
a handful of stable job functions RBAC
limits, regions, time windows, per-user variation ABAC (ideally as PBAC/policy-as-code)
sharing, ownership, hierarchies (Drive-style) ReBAC
users must control their own data’s access DAC at the edge
classified data, regulator-mandated MAC
third-party apps on your platform scopes + whatever governs your users

Real systems layer them: scopes at the edge, RBAC for staff, ABAC conditions for the risky actions, ReBAC for customer-facing sharing. The models compose because they all answer the same \(f(\text{subject}, \text{action}, \text{resource}, \text{context})\).

Pitfalls

QQuestionSelf-check

Why does “any authenticated user may GET /orders/{id}” fail even with perfect RBAC? Your refund rule gains a per-user limit and a business-hours condition — which model absorbs this cleanly, and what does the RBAC version look like? When is ReBAC worth its infrastructure?

ASolution

Role checks answer “may this kind of user call this endpoint” but not “may this user touch this order” — order 42 may belong to someone else. Authorization must include the resource term, or you have broken object-level authorization. The limit-and-hours rule is attribute logic: ABAC (as policy-as-code) keeps it one readable policy over user, resource, and context attributes; RBAC would force a new role per limit band and still couldn’t express time windows. ReBAC pays off when permissions follow relationships — ownership, sharing, folder hierarchies — because the permission already is a path in a graph; for stable job functions without sharing semantics, a role table is far cheaper to run.

Next: API Keys & Management (API Design #7) — issuing, scoping, rotating, and storing the credentials your machine clients actually use.