Start learning free

LESSON 31 OF 56 · SECURITY: ACCESS CONTROL

Don't Confirm What Exists in Python

Practice

Customers sign in with a token and look up or cancel their orders: Ana is customer 1 (token-ana-2b7f), Ben is customer 2 (token-ben-9d4c). Both routes get the order from find_order, which in the starting code fetches any order by its id, whoever owns it. The attack: Ben, signed in with a valid token, reads Ana's order 1 and cancels Ana's paid order 3.

An owner check that answers 403 for someone else's order would stop that, but it still leaks: 403 says "this order exists, it just isn't yours", and 404 says "no such order". By trying numbers, a visitor learns which orders exist and how many the shop has. The cancel route leaks the same way today: someone else's unpaid order answers 409, a missing one 404.

The fix: someone else's order must look exactly like a missing one, the way a login form says "Wrong email or password" for both mistakes. The routes already answer 404 when the lookup helper returns None, before any other check, as in this review route:

@app.get("/reviews/<int:review_id>")
def get_review(review_id):
    review = find_review(review_id)
    if review is None:
        return jsonify({"error": "Review not found"}), 404
    return jsonify(dict(review))

So one change in find_order covers every route that uses it.

GET  /orders/2           Ben       →  200  {"customer_id": 2, "id": 2, "ordered": "2026-03-15", "status": "paid"}
GET  /orders/1           Ben       →  404  {"error": "Order not found"}
GET  /orders/99          Ben       →  404  {"error": "Order not found"}
POST /orders/4/cancel    Ben       →  404  {"error": "Order not found"}
POST /orders/98/cancel   Ben       →  404  {"error": "Order not found"}
POST /orders/3/cancel    Ben       →  404  {"error": "Order not found"}
GET  /orders/3           Ana       →  200  {"customer_id": 1, "id": 3, "ordered": "2026-04-05", "status": "paid"}
POST /orders/6/cancel    Ben       →  409  {"error": "Only paid orders can be cancelled"}
POST /orders/2/cancel    Ben       →  200  {"id": 2, "status": "cancelled"}
GET  /orders/1           no token  →  401  {"error": "Login required"}

Your task: in find_order, below the query, return None when the order exists but its customer_id isn't current_customer(). Both routes then answer 404 "Order not found" for someone else's order, exactly as for a missing one.


Assignment
Follow the Coding Tutorial to make find_order hide other customers' orders.


Hint
Check order is not None first and join the two parts with and: for a missing order, reading order["customer_id"] would crash on None.


STEP 1 OF 2
    Ctrl + Enter to check

    Secx 404 Not 403 in Python

    Keep going with Python1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free