Start learning free

LESSON 64 OF 76 · SECURITY: FIND AND FIX

Project: Review a Search API

Practice

This is a review project. GET /search?q=…&sort=… returns the products whose name contains q, sorted by the column in sort (name by default). A security review found four holes, and each one is an attack a visitor can run:

  • SQL built from strings: the search glued q inside quotes: "WHERE name LIKE '%" + q + "%' ". Searching for x' UNION SELECT 1, service, secret FROM api_keys -- closed the quote and listed the shop's API keys as products. The review already took that line out, so for now the search ignores q and returns every product; you write the safe line.
  • A sort from the URL: sort is pasted after ORDER BY. A sort like CASE WHEN (SELECT substr(secret, 1, 1) FROM api_keys WHERE service = 'payments') = 'p' THEN name ELSE price END asks a yes-or-no question, and the order of the results answers it: by name means yes, by price means no. Letter by letter, the attacker reads the payments key.
  • Hidden products: Tea set has hidden = 1, pulled from sale, but every search still returns it.
  • Errors that print the SQL: when the database fails, the answer shows the error and the whole query, which tells an attacker the tables and columns to aim at.

Values and names: a value goes into SQL through a placeholder that sqlite3 fills, like :stars below. A column name or a word like desc can't be a placeholder, so it's checked against a fixed list:

DIRECTIONS = ["asc", "desc"]

@app.get("/reviews")
def reviews():
    direction = request.args.get("dir", "desc")
    if direction not in DIRECTIONS:
        return jsonify({"error": "dir must be asc or desc"}), 400
    values = {"stars": request.args.get("stars", 1, type=int)}
    query = "SELECT * FROM reviews WHERE stars >= :stars ORDER BY stars " + direction
    rows = db.execute(query, values).fetchall()

The check makes the database fail with a header, X-Test-Db-Error: database is locked, and reads what the shop logged at /_test/log. Once fixed, the shop must answer:

GET /search?q=tea  →  200  [{"id": 6, "name": "Teapot", "price": 22}]
GET /search?q=a&sort=price  →  200  [{"id": 7, "name": "Stapler", "price": 9}, {"id": 5, "name": "Plant", "price": 15}, {"id": 6, "name": "Teapot", "price": 22}, {"id": 3, "name": "Lamp", "price": 29}, {"id": 8, "name": "Gift card", "price": 50}]
GET /search?q=x' UNION SELECT 1, service, secret FROM api_keys --  →  200  []
GET /search?q=e&sort=CASE WHEN (SELECT substr(secret, 1, 1) FROM api_keys WHERE service = 'payments') = 'x' THEN name ELSE price END  →  400  {"error": "sort must be name or price"}
GET /search?q=e&sort=CASE WHEN (SELECT substr(secret, 1, 1) FROM api_keys WHERE service = 'payments') = 'p' THEN name ELSE price END  →  400  {"error": "sort must be name or price"}
GET /search?q=e&sort=secret  →  400  {"error": "sort must be name or price"}
GET /search?q=tea  (X-Test-Db-Error: database is locked)  →  500  {"error": "Search failed"}
GET /_test/log  →  200  ["database is locked in: SELECT id, name, price FROM products WHERE name LIKE :pattern AND hidden = 0 ORDER BY name"]

Your task: close the four holes and keep honest searches working. Keep a list SORT_COLUMNS of "name" and "price" and answer 400 for any other sort. Write the safe WHERE piece, with a :pattern placeholder that sqlite3 fills from values, and add AND hidden = 0. In the except block, log the full message with logging.error, then answer only "Search failed".


Assignment
Follow the Coding Tutorial to fix the four holes in the shop's search.


Hint
Each piece of the query ends with a space, so the pieces don't run together. In the except block, log message first and replace it after: logging.error writes what message holds at that moment.


STEP 1 OF 7
    Ctrl + Enter to check