Read Code Fast
Lesson 24 Security holes
injection, missing auth, trusted input, secrets, path traversal, eval and pickle
What you'll learn
- Follow outside input to the places where it becomes dangerous
- Spot SQL injection, path traversal, eval and client-side trust
- Keep secrets out of code
Security bugs don't crash. The code works perfectly, for the wrong person.
The idea
Anything that comes from outside is untrusted input: a form field, a URL, a file name, a request body. AI code is written for friendly input and works fine until someone is not friendly.
So follow each outside value to where it lands. Does it land in a SQL string, a file path, eval, pickle.loads, a shell command, or an "is this user allowed?" decision? If it lands there unchecked, that is the hole. Also look for secrets (keys and passwords) typed into the code: once committed, they are visible to everyone who ever sees the repo.
1import os2API_KEY = "sk_live_EXAMPLE_not_a_real_key"3REPORTS = "/srv/reports"45def find_user(db, email):6 sql = f"SELECT * FROM users WHERE email = '{email}'"7 return db.execute(sql).fetchall()89def read_report(name):10 with open(os.path.join(REPORTS, name)) as f:11 return f.read()1213@app.post("/orders/<order_id>/refund")14def refund_order(order_id):15 data = request.get_json()16 if data.get("is_admin"):17 refund(order_id, data["amount"])18 return "", 200
- Line 2 A secret in the code. It will be in git history forever. It belongs in an environment variable or a secrets manager.
- Line 6 The email is pasted into the SQL text with an f-string. Use
?placeholders, so the database gets the value separately from the command. - Line 10
namecomes from the user.os.path.joindoes not protect you: an absolute name or a..can leave/srv/reports. - Line 16 The client says whether it is an admin. The server must decide that from the logged-in session, never from the request.
Take away
- Follow every value that comes from outside to where it lands.
- SQL, file paths, eval and the "is this an admin?" decision are the places to look first.
- Never let the client tell the server who it is, and never keep a secret in the code.
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.