Start learning free

LESSON 30 OF 56 · SECURITY: ACCESS CONTROL

One Store's Data Stays in One Store in Python

Practice

This shop hosts several stores in one database. Every order has a store_id, and each store signs in with its own key in the X-Store-Key header: key-corner-5e1a is the Corner store (1), key-teahouse-c7d2 is the Teahouse (2). Keeping each store's data apart is called tenant isolation.

GET /orders already lists only the signed-in store's orders, but GET /orders/<id> and POST /orders/<id>/cancel look an order up by its id alone. The attack: the Corner store asks for order 5, which belongs to the Teahouse, reads it, and cancels it.

The rule: every query on orders also requires store_id to be the signed-in store. Another store's order then matches no row, so it looks exactly like a missing one: answer 404, never 403, which would confirm it exists. An UPDATE that matches no row doesn't fail, it just changes nothing; cursor.rowcount tells you how many rows changed:

cursor = db.execute("DELETE FROM reviews WHERE id = :review_id", {"review_id": 8})
db.commit()
print(cursor.rowcount)   # 1 if review 8 was deleted, 0 if there was none
GET  /orders             Corner    →  200  [{"id": 1, …}, {"id": 3, …}, {"id": 4, …}, {"id": 6, …}]
GET  /orders/3           Corner    →  200  {"id": 3, "ordered": "2026-04-05", "status": "paid"}
GET  /orders/5           Corner    →  404  {"error": "Order not found"}
POST /orders/5/cancel    Corner    →  404  {"error": "Order not found"}
GET  /orders/5           Teahouse  →  200  {"id": 5, "ordered": "2026-05-07", "status": "paid"}
POST /orders/99/cancel   Corner    →  404  {"error": "Order not found"}
POST /orders/1/cancel    Corner    →  200  {"id": 1, "status": "cancelled"}
GET  /orders/1           Teahouse  →  404  {"error": "Order not found"}
GET  /orders             no key    →  401  {"error": "Store key required"}

Your task: in get_order and in cancel_order, add a piece below the WHERE piece of the query that also requires store_id to equal :store_id. Then, in cancel_order, below db.commit(), answer {"error": "Order not found"} with status 404 when cursor.rowcount is 0.


Assignment
Follow the Coding Tutorial to add the store to both queries and a 404 for a cancel that changed nothing.


Hint
values already holds the signed-in store under the key "store_id", so :store_id in the SQL is filled from it. The query is built from string pieces, so start the new piece with AND.


STEP 1 OF 4
    Ctrl + Enter to check

    Secx Tenant Isolation 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