Lesson 17 / 25
Security Flaws in Generated Code
Recognise injection, hard-coded secrets and weak defaults, and fix them.
Insecure patterns are common in training data
Models learned from a lot of code that was written quickly or insecurely, so they can reproduce SQL built from strings, disabled certificate checks, hard-coded credentials, weak hashing or overly broad permissions. Treat security-sensitive output as untrusted: check every place user input meets a database, a shell, a file path or HTML, and run a scanner on the result.
SQL injection, demonstrated
I ran this against an in-memory SQLite database. The string-built query returns every user for a crafted input; the parameterised query returns nobody, which is correct.
import sqlite3
db = sqlite3.connect(":memory:")
db.execute("create table users(name text, secret text)")
db.executemany("insert into users values (?,?)", [("asha","a1"),("ravi","r2")])
def find_bad(name):
return db.execute(f"select name from users where name = '{name}'").fetchall()
def find_ok(name):
return db.execute("select name from users where name = ?", (name,)).fetchall()
evil = "x' OR '1'='1"
print(find_bad(evil), find_ok(evil))
Output:
[('asha',), ('ravi',)] []Ask for a security review, then verify
Asking the assistant "list security problems in this code" often finds real issues, a useful second look. But it is not a guarantee, so keep static analysis, dependency scanning and human review in your pipeline.
Quick check: How do you prevent SQL injection in generated database code?
- Hide the database
- Build SQL with string formatting
- Use parameterised queries
- Use shorter variable names
Answer
Use parameterised queries — Placeholders keep user input as data, never as part of the SQL command.