Sub topic 8
Reviewing for security flaws
This chapter assumes you can read a Git diff, write basic Python, and run unit tests. It covers the security problems that appear most often in AI-generated code and how to find them in a diff.
Why AI code needs a security pass
An AI assistant predicts code that looks like the code it was trained on. Much of that code is tutorial code, which skips validation and takes shortcuts. The assistant also does not know your threat model, such as who calls this function or whether the input comes from an untrusted user. Treat its output as a pull request from an unfamiliar author and ask where untrusted data enters and where it ends up.
Injection
Injection happens when untrusted input is built into a command or query as text, so the interpreter reads it as instructions. SQL injection is the classic case.
import sqlite3
def find_user_unsafe(conn: sqlite3.Connection, name: str):
# Builds SQL by string formatting: vulnerable to injection.
query = f"SELECT id, name FROM users WHERE name = '{name}'"
return conn.execute(query).fetchall()
def find_user(conn: sqlite3.Connection, name: str):
# Parameterized query: the driver treats name as data, not SQL.
return conn.execute(
"SELECT id, name FROM users WHERE name = ?", (name,)
).fetchall()Call find_user_unsafe with "' OR '1'='1". The query becomes WHERE name = '' OR '1'='1', which is true for every row, so the function returns the whole table. find_user treats the same string as a literal name and returns nothing.
In a diff, look for f-strings, % formatting, .format(), or + concatenation that feeds a database call, os.system, subprocess with shell=True, eval, or a template. The fix is the same each time: pass untrusted values as separate parameters, never as part of the command text.
Hardcoded secrets
Assistants often write example values straight into code, such as API_KEY = "sk-test-123". A real key pasted into a prompt can also end up in the output. Search the diff for tokens, passwords, connection strings, and private keys. Secrets belong in environment variables or a secrets manager. If a real secret was committed, rotate it, because deleting it from the next commit does not remove it from history.
Missing input validation
Check every value that crosses a trust boundary, such as an HTTP request, a file upload, or a message from a queue. Ask whether the code checks type, length, range, and allowed characters. File paths need extra care. A user-supplied name like ../../etc/passwd can escape the intended folder unless you resolve the path and confirm it stays inside it.
Other patterns to look for
| Pattern in the diff | Risk | Safer choice |
|---|---|---|
| `verify=False` on HTTP requests | Disables TLS certificate checks | Keep verification on |
| `pickle.loads` on outside data | Runs arbitrary code | Use JSON or another data-only format |
| `md5` or `sha1` for passwords | Easy to crack | Use bcrypt, scrypt, or argon2 |
| Broad CORS or `0.0.0.0` binding | Exposes the service | Allow only what is needed |
| Error messages that include stack traces | Leaks internals | Log details, return a generic message |
A review routine
Run the checks the tools can do for you as well. A security linter such as Bandit flags many of the patterns above, and a secret scanner catches committed keys. Tools miss logic flaws, such as an endpoint that never checks who the caller is, so you still need to read the code.
Exercise
An assistant wrote subprocess.run(f"convert {filename} out.png", shell=True), where filename comes from an upload form. What is the flaw, and how do you fix it?
Show answer
The filename is untrusted and is built into a shell command, so a name like a.jpg; rm -rf ~ runs extra commands (command injection). Pass the arguments as a list without a shell, for example subprocess.run(["convert", filename, "out.png"], check=True). Also validate the filename and the file type.
Exercise
A diff adds DB_PASSWORD = "hunter2" to settings.py. Is it enough to change the line in a follow-up commit?
Show answer
No. The password stays in Git history. Treat it as exposed and rotate it, then read the new value from an environment variable or a secrets manager.