Start learning free

LESSON 36 OF 76 · SECURITY: INJECTION

Sort by a Column Name Safely

Practice

The shop's GET /products sorts its list by ?sort=. The starting code glues that text onto the end of its SQL, right after ORDER BY, so whatever a visitor sends becomes part of the SQL code. Even ?sort=stock works: it sorts by a column this route never shows.

The attack: SQL can sort by a question. A visitor sends ?sort=CASE WHEN (SELECT substr(secret, 1, 1) FROM api_keys WHERE service = 'payments') = 'p' THEN name ELSE price END, and the list comes back sorted by name if the payments key starts with p, and by price if it doesn't. The attacker gets your payment service's secret key, one letter per guess, just by watching the order of the list.

The fix: a ? placeholder can't help here. It always stands for a value, so ORDER BY ? filled with "price" sorts every row by the same text, and nothing gets sorted. A column name has to be written into the SQL, so it must be text you wrote yourself: keep an allowlist, a dict from the names a visitor may send to the column each one means, and refuse everything else. The same idea on a reviews page that sorts up or down:

DIRECTIONS = {"up": "ASC", "down": "DESC"}

@app.get("/reviews")
def list_reviews():
    order = request.args.get("order", "up")
    if order not in DIRECTIONS:
        return jsonify({"error": "order must be up or down"}), 400
    query = "SELECT stars, text FROM reviews ORDER BY stars " + DIRECTIONS[order]
    ...

Your code must answer these requests. created means the order the products were added in, which is the order of the id column:

GET /products?sort=price    →  200  [{"name": "Pen", "price": 2}, {"name": "Notebook", "price": 7}, …]
GET /products?sort=created  →  200  [{"name": "Mug", "price": 12}, {"name": "Notebook", "price": 7}, …]
GET /products               →  200  [{"name": "Gift card", "price": 50}, {"name": "Lamp", "price": 29}, …]
GET /products?sort=stock    →  400  {"error": "sort must be name, price or created"}
GET /products?sort=CASE WHEN … THEN name ELSE price END  →  400  {"error": "sort must be name, price or created"}

Your task: add a dict SORT_COLUMNS that maps name to name, price to price and created to id. In list_products, answer 400 with the error above when sort is not one of its keys; otherwise replace sort with its column before the query is built.


Assignment
Follow the Coding Tutorial to put an allowlist between ?sort= and the ORDER BY of GET /products.


Hint
in on a dict checks its keys. After the check, look the name up in the dict, so only its values, which you wrote yourself, ever reach the SQL.


STEP 1 OF 4
    Ctrl + Enter to check