如何修复AI编写的不安全SQL
AI代理使用字符串插值而不是参数化语句构建SQL查询,从而将SQL注入漏洞引入生产数据库代码中。
CursorClaude CodeCodexWindsurf PostgreSQLTypeScript
代理使用模板字面量构建SQL查询,创建了经典的SQL注入向量,这些向量在测试中看似正常,但在生产环境中可被利用。
症状
用户控制的值直接插值到SQL字符串中。
// WRONG — SQL injection vulnerabilityasync function getUserByEmail(email: string) { const result = await db.query( `SELECT * FROM users WHERE email = '${email}'` // ^^^^^^^ attacker-controlled ); return result.rows[0];}
// Attacker input: ' OR '1'='1// Resulting query: SELECT * FROM users WHERE email = '' OR '1'='1'// Returns every row in the table.发生原因
模板字面量是JavaScript中最自然的字符串构建工具,模型训练时使用的许多教程示例都使用它们来构建SQL语句而不进行参数化。代理也没有模拟恶意输入——它假设传递的是格式良好的数据。
如何识别
- 包含
${...}插值的SQL字符串。 - 接受用户输入并将其传递给原始查询助手但没有单独参数数组的查询函数。
- 使用单个参数调用
db.query(sql)而不是db.query(sql, [params])。 LIKE '%${term}%'模式。
如何修复
始终使用参数化查询。数据库驱动处理转义;您的代码从不接触引号。
// CORRECT — parameterized query (node-postgres / pg)async function getUserByEmail(email: string) { const result = await db.query( "SELECT id, name, email FROM users WHERE email = $1", [email] // second argument: params array ); return result.rows[0] ?? null;}
// CORRECT — with Postgres.js (template tag)async function searchUsers(term: string) { return sql`SELECT id, name FROM users WHERE name ILIKE ${"%" + term + "%"}`; // postgres.js automatically parameterizes template expressions}[ ] No ${...} inside raw SQL strings — use $1/$2 placeholders instead[ ] Every db.query() call passes user input via the params array, not the SQL string[ ] Use an ORM (Prisma, Drizzle) or query builder for complex queries[ ] LIKE wildcards are appended in the param value, not concatenated into the SQL[ ] Run sqlfluff or a SQL linter in CI to catch interpolated strings修复提示
This SQL query uses string interpolation with user-supplied values, which is aSQL injection vulnerability. Rewrite every raw query to use parameterizedstatements ($1, $2 placeholders for pg, or the tagged template literal form forpostgres.js). Never interpolate variables directly into SQL strings. If thequery is complex, migrate it to Prisma or Drizzle ORM instead.测试
# Detect template literal interpolation inside SQL-looking stringsgrep -rn 'query(`\|sql`\|execute(`' --include="*.ts" --include="*.tsx" . \ | grep '\${' \ | grep -v "node_modules" \ && echo "FAIL: interpolated SQL found" || echo "OK"