Why Your AI Coding Assistant Keeps Generating Security Vulnerabilities
AI coding assistants are systematically biased toward insecure code. After auditing 14 codebases, here are the 6 vulnerability patterns AI generates most and how to stop them.
Last month I ran a security audit on a codebase where AI generated roughly 60% of the code. I found 23 security vulnerabilities. Twenty of them were in AI-generated code. That's not a coincidence. It's a pattern I've seen in every AI-heavy codebase I've reviewed.
A 2022 study, revised in 2023, found that participants using a codex-davinci-002 assistant wrote less secure solutions on the studied tasks and were more confident in their security. That result concerns that model and experiment. Check the security of the code your current tools produce.[1]
After reviewing 14 codebases, I've cataloged the specific vulnerability patterns that AI generates most frequently. These aren't theoretical. Every one of these appeared in production code.
AI generates endpoint handlers that process requests without verifying the user has permission. It happens because most code examples in training data skip auth for brevity.
typescript
// What AI generates (vulnerable):app.get("/api/users/:id/billing", async (req, res) => { const billing = await getBillingInfo(req.params.id); res.json(billing);});// What it should generate:app.get("/api/users/:id/billing", authMiddleware, async (req, res) => { if (req.user.id !== req.params.id && !req.user.isAdmin) { return res.status(403).json({ error: "Forbidden" }); } const billing = await getBillingInfo(req.params.id); res.json(billing);});
In one audit, I found 11 API endpoints that AI generated without authentication. Three of them exposed billing data. The team had auth middleware available. The AI just didn't use it.
# Antipattern 2: SQL Injection via String Concatenation
SQL injection can occur when untrusted values become part of the query syntax. Use parameterized queries or a correctly parameterizing query builder, and review raw SQL paths carefully.[2]
typescript
// AI-generated (vulnerable):const query = `SELECT * FROM orders WHERE status = '${status}' AND user_id = '${userId}'`;const results = await db.raw(query);// Safe version:const results = await db("orders") .where({ status, user_id: userId });
For browser access to sensitive responses, configure the intended origins explicitly. CORS controls which browser origins can read a response. It does not block non-browser clients or replace authentication and authorization.[3]
typescript
// AI-generated (vulnerable):app.use(cors({ origin: "*" }));// What production needs:app.use(cors({ origin: process.env.ALLOWED_ORIGINS?.split(",") || [], credentials: true, methods: ["GET", "POST", "PUT", "DELETE"],}));
AI generates code with placeholder secrets that look real enough to pass casual review. I've found API keys, JWT secrets, and database passwords hardcoded in AI-generated code that made it to production.
typescript
// AI-generated (vulnerable):const JWT_SECRET = "your-secret-key-here";// Also AI-generated (still vulnerable, just sneakier):const JWT_SECRET = process.env.JWT_SECRET || "fallback-secret-key";// That fallback means the app works without the env var set.// In production, if the env var is missing, you're running// with a guessable secret.
The fallback pattern is particularly dangerous because it passes code review. The reviewer sees the process.env reference and assumes it's secure.
Validate incoming fields before using them, including their type, length and permitted values. Authentication and authorization are separate checks. The example assumes authMiddleware populates req.user and still needs a check that the user may comment on the selected post.[4]
Figure 1. Validate and authorize requests before writing application data.
# Antipattern 6: Information Leakage in Error Responses
AI catches errors and sends the raw error message to the client. Stack traces, database column names, and internal system details leak through error responses.
typescript
// AI-generated (leaks info):app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: err.message, stack: process.env.NODE_ENV === "development" ? err.stack : undefined, });});// That NODE_ENV check? AI doesn't know if it's set in production.
I've developed a prompting pattern that reduces AI security vulnerabilities by roughly 80%. I call it the SHIELD prompt prefix.
Before any AI code generation that touches user data or API endpoints, prepend this context:
Security requirements for this code:
- All endpoints must use [your auth middleware name]
- All user input must be validated with Zod schemas
- No string concatenation in database queries
- No hardcoded secrets (fail if env var is missing, no fallbacks)
- Error responses must not expose internal details
- CORS must be restricted to ALLOWED_ORIGINS env var
- All file uploads must validate type and size
Sounds simple. But it works because it flips the AI's default from "make it work" to "make it work securely." The 80% reduction came from tracking vulnerabilities before and after implementing this prompt prefix across a team of 9 engineers over 3 months.
Use automated checks alongside review and tests. Secretlint needs a configured rule set before it can scan the selected files.[5]
bash
# Add to your CI pipeline# Run your configured lint and code-security analysis.# A blanket tagged-template ban also rejects safe parameterized APIs.npx eslint src/# Install and initialize Secretlint once, then commit its configuration:npm install --save-dev secretlint @secretlint/secretlint-rule-preset-recommendnpx secretlint --init# Run the configured scanner in CI:npx secretlint "src/**/*.ts"# Check for known vulnerabilities in dependenciesnpm audit --audit-level=high
Code scanning can identify supported classes of security problems. Investigate the findings, test application-specific controls and retain human review because a scan does not establish that the application is secure.[6]
Figure 2. Scanners, tests and review provide different evidence about a change.
AI doesn't generate insecure code because it's stupid. It generates insecure code because security is a constraint, and AI optimizes for the primary objective: working code. You need to make security part of the prompt context, part of the automated checks, and part of the review checklist.
Stop trusting AI-generated code with your users' data. Verify every endpoint, validate every input, and automate every security check you can. The 30 minutes you spend setting up security automation will save you from the breach that takes months to recover from.
Frequently asked questions
Does a secure prompt guarantee secure generated code?
A prompt can state the application's security requirements, but its output still needs verification. Review the implementation, run relevant tests and use scanners for the issue classes they can detect. The team remains responsible for approval.
Is an internal API exempt from runtime validation?
Data from an internal API can still cross a trust boundary. Validate the fields and business constraints required by the receiving component, and check authorization separately. A valid identifier alone does not establish permission to access its record.
Does a CORS allowlist protect an API from every client?
CORS tells a browser which origins may read responses. It does not stop requests from non-browser clients and does not replace authentication or authorization. Select an origin policy that matches the data and intended browser consumers.
Which security checks should run automatically?
Use appropriate code scanning, secret detection and dependency auditing alongside tests for authorization and invalid input. Configure the tools first, examine their findings and retain review of application-specific security behaviour.
Five predictions for where code intelligence is heading by 2028, based on 6 years of building tools in this space. Includes what's real, what's overhyped, and a maturity model for planning.
Most code quality dashboards fail because they track too many metrics and live outside the team's workflow. Here are exactly 7 metrics and a 3-week adoption plan that actually works.
Build software composition analysis into CI with dependency inventories, vulnerability checks and licence review. Define owners, response targets and follow-up.
Architecture fitness functions are automated tests for your system's structural properties. Here's how to implement the 5 most impactful ones and integrate them into your CI pipeline.
Apply developer documentation best practices with ADRs, comments and tested examples. Use the WRITE system to keep changes reviewable and find stale guidance.