⚠️ Critical Security Fix: Transform PostgreSQL queries to use parameterized queries and prevent SQL injection vulnerabilities (CWE-89).
This codemod automatically transforms PostgreSQL queries in Express applications that use string concatenation or template literals into safe parameterized queries using the pg (node-postgres) library.
SQL injection occurs when user input is directly concatenated into SQL query strings, allowing attackers to manipulate the query structure and potentially:
// Before
app.get('/user/:id', (req, res) => {
client.query(`SELECT * FROM users WHERE id = ${req.params.id}`)
.then(result => res.json(result.rows))
});
// After
app.get('/user/:id', (req, res) => {
client.query('SELECT * FROM users WHERE id = $1', [req.params.id])
.then(result => res.json(result.rows))
});
Middleware Function
javascript
// Before
const authenticate = async (req, res, next) => {
const user = await db.query(`SELECT * FROM users WHERE token = '${req.headers.authorization}'`);
// ...
};
// After
const authenticate = async (req, res, next) => {
const user = await db.query('SELECT * FROM users WHERE token = $1', [req.headers.authorization]);
// ...
};
🔍 Why This Matters
Vulnerable Code Example
javascript
// DANGEROUS: SQL Injection vulnerability
app.post('/login', (req, res) => {
const { email, password } = req.body;
client.query(`SELECT * FROM users WHERE email = '${email}' AND password = '${password}'`)
});
// Attacker input: email = "admin@example.com' OR '1'='1' --"
// Resulting query: SELECT * FROM users WHERE email = 'admin@example.com' OR '1'='1' --' AND password = '...'
// This bypasses authentication!
Secure Code After Transformation
javascript
// SECURE: Uses parameterized queries
app.post('/login', (req, res) => {
const { email, password } = req.body;
client.query('SELECT * FROM users WHERE email = $1 AND password = $2', [email, password])
});
// Attacker input is safely escaped as a parameter value
// No SQL injection possible
🏗️ Development
bash
# Run tests
pnpm test
# Test on specific case
pnpm test tests/template-literal
# Update test snapshots
pnpm test -u
# Validate workflow
npx codemod validate -w workflow.yaml