AlgoViz

API authorization

medium 24 min

Authorization decides what a known caller may do, to which object, right now.

See it run

Roles, owners, situations and scopes: follow each decision to allow or deny.

Operations

Read a role's rights

The permission matrix of a shop, one role at a time.

Step 1 of 5

Customer

CustomerSellerAdmin
View productsyesyesyes
Create productnoyesyes
Edit productnoownyes
Delete productnonoyes
Own cartownnoyes
Place orderyesnoyes
View ordersownown salesyes
Manage usersnonoyes

Customers view products and place orders. Cart and orders are their own only.

Step 1: Customer

def permissions_of(user):    found = set(user.permissions)    for role in user.roles:        found |= ROLE_PERMISSIONS.get(role, set())    return found
Needs
Role only
Denied with
403

Each cell that says own needs a second check.

In the real world

The same api authorization doing real jobs. Pick one and step through it.

The most common authorization hole, and its fix.

Step 1 of 3

Their own order

OwnerAsked byAnswer
1001AnnAnn200
1002Ben--

Ann asks for order 1001, which is Ann's.

Step 1: Their own order

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Checking only in the browser

    critical

    Anyone can call the API without your page.

    Wrong
    if user.role == "admin": show_delete_button()
    Right
    def delete(user, id):    if not allowed(user, "products:delete"):        return 403
  • Forgetting the object

    critical

    A logged-in user changes an ID and sees other people's data.

    Wrong
    order = db.get(order_id)
    Right
    order = db.get(order_id, tenant=user.tenant,               customer=user.id)
  • Allowing by default

    critical

    Every new action is open until someone remembers to block it.

    Wrong
    if action in blocklist: return Falsereturn True
    Right
    return action in allowlist
  • Admin for one small need

    major

    One stolen account then holds everything.

    Wrong
    user.roles.append("admin")
    Right
    user.permissions.add("reports:read")

Interview tips

  • Explain it in one line

    • What may this caller do, to which object, right now?
  • GUARD

    • Grant minimum.
    • Use roles.
    • Always server-side.
    • Reject by default.
    • Document scopes.
  • Choose the model

    • Few jobs: roles and ownership.
    • Time, place, state: attributes.
    • Sharing: relationships.
    • Other apps: scopes.
  • Expect these questions

    • How do you isolate tenants?
    • What if a role is removed?
    • How do you check a list?