Start learning free

LESSON 49 OF 76 · SECURITY: ACCESS CONTROL

Permissions, Not Role Names

Practice

This shop has three kinds of account: customers like Ana, support staff like Sam, and admins like Max. Each staff route is wrapped in @requires(...) and names what it needs, such as "orders:refund", but the decorator only checks that the token belongs to someone. The attack: Ana, a customer, signs in with a valid token, refunds an order and sets product 6's price to 1, and the shop answers 200 every time.

A quick fix is if user["role"] != "admin" in each route. It breaks as soon as roles change: support staff must refund orders too, and every new role means editing many routes. Instead, keep one table of permissions for each role. A route names a permission, never a role, and one check in the decorator compares the two:

PERMISSIONS = {"editor": ["reviews:delete"]}

@app.delete("/reviews/<int:review_id>")
@requires("reviews:delete")
def delete_review(user, review_id):
    ...

A role the table doesn't name, like "customer", gets no permissions: .get(role, []) gives it an empty list. No token is still 401 ("who are you?"); a known account whose role lacks the permission gets 403 ("you may not do this"). Tokens go in Authorization: Bearer …: Ana token-ana-71c2, Sam token-sam-4e8a, Max token-max-9b3d.

GET  /orders/1                        Ana       →  403  {"error": "Not allowed"}
POST /orders/1/refund                 Ana       →  403  {"error": "Not allowed"}
PUT  /products/6/price {"price": 1}   Ana       →  403  {"error": "Not allowed"}
GET  /orders/1                        Sam       →  200  {"customer_id": 1, "id": 1, "status": "paid"}
POST /orders/2/refund                 Sam       →  200  {"id": 2, "status": "refunded"}
PUT  /products/6/price {"price": 1}   Sam       →  403  {"error": "Not allowed"}
GET  /orders/2                        Max       →  200  {"customer_id": 2, "id": 2, "status": "refunded"}
POST /orders/5/refund                 Max       →  200  {"id": 5, "status": "refunded"}
PUT  /products/6/price {"price": 20}  Max       →  200  {"id": 6, "price": 20}
GET  /orders/1                        no token  →  401  {"error": "Login required"}

Your task: below ACCOUNTS, add a PERMISSIONS dict that gives "support" the permissions "orders:read" and "orders:refund", and "admin" those two plus "products:edit". Then, in wrapper, below the 401 check, answer {"error": "Not allowed"} with status 403 when the route's permission isn't in the list of the user's role.


Assignment
Follow the Coding Tutorial to add the permissions table and the 403 check inside requires.


Hint
Look the role up with .get(user["role"], []), so a role with no row, like "customer", gets an empty list instead of a KeyError. A permission that isn't in that list means 403.


STEP 1 OF 5
    Ctrl + Enter to check