CY3: Secure code: fixing flaws with proof

Lesson 2 of 5 · reading 15–25 minutes; practice and project time is on the module page

Injection and parameterised queries

🎯You'll be able to

Recognise a query built from raw text and rewrite it with placeholders so that input is always treated as data.

🏠The everyday picture

A form with boxes, "Name: ___", can't change what the form asks, whatever is written in the box. A blank sheet where someone writes both the question and the answer can say anything.

📘What it really is

📝A worked example

Input: the starter's search_patients, and the search text x' OR '1'='1' --.

Steps:

  1. Read the starter code: the text is pasted into the query.
  2. Predict the result: the quote closes the text, OR '1'='1' is true for every row, and -- turns the rest into a comment. Every patient is returned.
  3. Rewrite with a placeholder and pass f"%{name}%" as a value. The same input is now just a strange name, and no patient matches.

Expected output: the fixed function returns [] for that input, and finds Test Patient D'Souza for D'Souza.

🌍Where it's used

📝Case scenario

A coaching institute's student portal failed whenever a student with an apostrophe in their name searched for their results. The developer added code to delete apostrophes, which broke names. A reviewer replaced the query with placeholders, and both the error and the hidden injection flaw disappeared.

🖱️Try it

In the kit's starter folder, run python -m pytest tests/test_fixes.py -k "01 or 02". Success: both tests fail, and you can say from the failure messages which line of app/bookings.py causes them.

⚠️Common mistakes

🛠️For your project

Tests 1 and 2 in tests/test_fixes.py check that the injection input returns nothing and that D'Souza is found.

✅Quick check

Why does x' OR '1'='1' -- return every row from a query built by pasting text?

Show the answer

The quote ends the text, the OR makes the condition always true, and -- hides the rest.

Where does the % go in a parameterised LIKE search?

Show the answer

In the value you pass, not in the query text.

← PreviousNever trust input
ProLearners Assist