Sub topic 8
Reviewing for security flaws
This chapter assumes you can read a Git diff, write basic SQL and HTTP handler code, and run unit tests. It covers the security flaws that most often appear in AI-generated code and how to find them in a diff.
Why security needs its own pass
An AI assistant optimizes for code that works and looks like the examples it learned from. Many of those examples are tutorials, snippets, and old answers that skip security. The result is code that passes a happy-path test and still has a vulnerability.
Security flaws are hard to catch by running the code. The feature works for normal users. The flaw only shows up when someone sends hostile input. So you have to look for it on purpose, by reading the diff with an attacker's mindset.
Treat the AI's output as an untrusted contribution. Ask of every line: where does this data come from, and what happens if the sender is malicious?
Trace data from sources to sinks
The most useful habit is to trace data from where it enters to where it is used.
- A source is any place data enters the program from outside: HTTP parameters, headers, cookies, uploaded files, environment variables, database rows written by users, and responses from other services.
- A sink is any place where data can do damage: a SQL query, a shell command, a file path, an HTML page, a deserializer, or a URL fetch.
For each sink in the diff, walk backward to the source. If untrusted data reaches the sink without validation or the correct escaping, you have found a candidate flaw.
Injection
Injection happens when untrusted input is mixed into a command or query as if it were code. SQL injection is the classic case, and AI assistants still produce it, especially when asked for "a quick function" or when the surrounding code already builds strings.
The two functions below show the difference.
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()If you call find_user_unsafe with the name ' OR '1'='1, the query becomes WHERE name = '' OR '1'='1', which is true for every row. The function returns the whole table. find_user treats the same text as a literal name and returns nothing.
In a diff, look for these patterns:
- f-strings,
%formatting,.format(), or+used to build SQL. os.system,subprocesswithshell=True, orexec/evalon input.- Template strings that put user data into HTML without escaping, which leads to cross-site scripting (XSS).
- File paths built from user input, such as
open("uploads/" + filename). A filename like../../etc/passwdescapes the folder. This is called path traversal.
The fix is the same idea each time: keep code and data separate. Use parameterized queries, pass command arguments as a list without a shell, use the framework's auto-escaping templates, and resolve file paths and check that they stay inside the allowed directory.
Hardcoded secrets
Assistants often write examples with placeholder credentials, and sometimes those placeholders look real, or you paste a real key into the prompt and it comes back in the code. Check the diff for:
- API keys, tokens, passwords, and private keys in source files.
- Connection strings with embedded passwords.
- Default admin credentials, such as
admin/admin. - Secrets in test fixtures, example config files, or comments.
Secrets belong in environment variables or a secrets manager. If a real secret ever appears in a diff, treat it as exposed. Rotate it, even if you delete the line before committing, because it may already be in your prompt history or logs.
A quick scan of the staged changes helps:
git diff --staged | grep -n -i -E "(api[_-]?key|secret|token|passw(or)?d)\s*[:=]"This is a cheap filter, not a guarantee. A dedicated secret scanner such as gitleaks or trufflehog catches more.
Missing input validation
AI code often trusts its inputs. Look for handlers that read a field and use it directly.
Check each input for:
- Type and shape. Is a number really a number? Is a list really a list?
- Range and length. Can a quantity be negative? Can a string be a gigabyte long?
- Allowed values. If a field should be one of three options, is that enforced?
- Where validation happens. Checks in the browser do not count. Validation must run on the server.
A common example is a price or quantity taken from the request body. If the client sends {"quantity": -5}, a naive total goes negative and the store owes the customer money.
Authentication and authorization
These are two different questions. Authentication asks who you are. Authorization asks what you are allowed to do.
AI-generated endpoints often check the first and forget the second. A handler that loads /invoices/{id} for any logged-in user is vulnerable to insecure direct object reference (IDOR). Any user can read any invoice by changing the ID.
When reviewing a new route, ask:
- Does it require a logged-in user?
- Does it check that this user owns, or may access, the specific record?
- Are admin-only actions guarded by a role check on the server?
- Does the assistant's change quietly remove or loosen an existing check to make a test pass?
The last question matters. When a test fails with a 403 error, an assistant may "fix" it by weakening the permission check. Scan the diff for deleted decorators, removed middleware, and conditions that became or True.
Cryptography and randomness
Assistants reproduce old patterns. Watch for:
| Pattern in the diff | Problem | Better choice |
|---|---|---|
| `md5` or `sha1` for passwords | Fast hashes are cracked quickly | `argon2`, `bcrypt`, or `scrypt` |
| `random.randint` for tokens | Predictable output | `secrets.token_urlsafe` |
| Custom encryption code | Easy to get wrong | A vetted library such as `cryptography` |
| `verify=False` in HTTP clients | Disables certificate checks | Leave verification on |
| Hardcoded encryption keys or IVs | Anyone with the source can decrypt | Load keys from a secrets store |
Unsafe deserialization and risky defaults
Some functions run code when they load data. pickle.loads on untrusted bytes and yaml.load without a safe loader can both lead to remote code execution. Prefer JSON, or yaml.safe_load.
Also look for risky defaults the assistant may add to make something "just work":
DEBUG = Truein production settings.- CORS set to allow every origin with credentials.
- Servers bound to
0.0.0.0with no authentication. - Error responses that return stack traces or SQL text to the client.
- Overly broad permissions, such as
chmod 777or an IAM policy with"Action": "*".
Logging and data exposure
Check what the new code writes to logs and responses. Assistants like to add helpful print or logger.info calls that include whole request bodies, which can contain passwords, tokens, and personal data. Return only the fields a client needs, not the entire database record.
Dependencies with security impact
A new package is new attack surface. The earlier chapter on verifying packages covers whether a package exists. For security, also confirm that the version is maintained, that it is not pinned to a release with a known vulnerability, and that the name is not a lookalike of a popular library. Run your ecosystem's audit tool, such as pip-audit or npm audit, after the change.
A practical review pass
Use this order on any change that touches input, data, or permissions:
- List every new source and sink in the diff.
- Trace each sink back to its source and note the control in between.
- Search for secrets and risky defaults.
- Check authorization on each new route or action.
- Run a static security scanner, such as
banditfor Python, and read its findings. - Write a hostile-input test for each risk you found.
Step 6 turns your review into lasting evidence. A test such as the one below fails if someone reintroduces string-built SQL.
import sqlite3
def find_user(conn: sqlite3.Connection, name: str):
return conn.execute(
"SELECT id, name FROM users WHERE name = ?", (name,)
).fetchall()
def test_find_user_treats_injection_text_as_data():
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users (id INTEGER, name TEXT)")
conn.execute("INSERT INTO users VALUES (1, 'alice'), (2, 'bob')")
assert find_user(conn, "' OR '1'='1") == []
assert find_user(conn, "alice") == [(1, "alice")]
if __name__ == "__main__":
test_find_user_treats_injection_text_as_data()
print("ok")Edge cases in security review
- Safe in one place, unsafe in another. A function may be safe today because its only caller validates input. If the assistant adds a second caller, the assumption breaks. Prefer controls inside the function that touches the sink.
- Second-order injection. Data stored safely and later read back into a query or page can still be dangerous. Database rows are a source, not a trusted place.
- Fixes that move the problem. Parameterizing values does not protect table or column names. If the assistant builds an
ORDER BYfrom user input, check it against an allowlist of column names. - Confident explanations. The assistant may say "this is secure" in its summary. That statement is not evidence. Only your trace, scans, and tests count.
Exercise
An assistant adds this handler: @app.get("/reports/<int:report_id>") that requires login and returns Report.query.get(report_id). The query uses the ORM, so SQL injection is not a concern. Name the security flaw you should check for, and describe one fix and one test you would add.
Show answer
The flaw is missing authorization (an insecure direct object reference). The route checks that the user is logged in but not that the report belongs to them, so any user can read any report by changing the ID. The fix is to filter by owner, for example Report.query.filter_by(id=report_id, owner_id=current_user.id).first_or_404(), or to check ownership and return 403 or 404. The test logs in as user A, requests a report owned by user B, and asserts that the response is 403 or 404 and not 200.
Exercise
A diff builds a command with subprocess.run(f"convert {filename} out.png", shell=True) where filename comes from an upload. Explain the risk and rewrite the call safely.
Show answer
With shell=True, a filename such as x.png; rm -rf ~ is interpreted by the shell, so the attacker can run arbitrary commands (command injection). Pass the arguments as a list and drop the shell: subprocess.run(["convert", filename, "out.png"], check=True). Also validate the filename, for example by generating your own name for the stored file, and reject names that begin with - so they cannot be read as options.