Skip to content

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.

10 min read
Illustrative cutaway charcoal metal enclosure reveals a fine steel-mesh barrier with one small vulnerable gap, next to a precisely fitted teal reinforcement insert.
On this page

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]

The 6 Security Antipatterns AI Generates

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.

Antipattern 1: Missing Authentication Checks

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 });

Antipattern 3: Overly Permissive CORS

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"],
}));

Antipattern 4: Hardcoded Secrets and Keys

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.

Antipattern 5: Missing Input Validation

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]

Authentication establish identity Input validation check fields Authorization check permission Data access apply the change
Figure 1. Validate and authorize requests before writing application data.
typescript
// AI-generated (vulnerable):
app.post("/api/comments", async (req, res) => {
  const { content, postId } = req.body;
  const comment = await prisma.comment.create({
    data: { content, postId, userId: req.user.id },
  });
  res.json(comment);
});

// Secure version with validation:
import { z } from "zod";

const CommentSchema = z.object({
  content: z.string().trim().min(1).max(5000),
  postId: z.string().uuid(),
});

app.post("/api/comments", authMiddleware, async (req, res) => {
  const result = CommentSchema.safeParse(req.body);
  if (!result.success) {
    return res.status(400).json({ errors: result.error.issues });
  }
  const comment = await prisma.comment.create({
    data: {
      content: result.data.content,
      postId: result.data.postId,
      userId: req.user.id,
    },
  });
  res.json(comment);
});

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.

The Security Prompt Framework

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.

The AI Security Checklist

Every PR with AI-generated code should pass this checklist:

Check What to Look For
Auth Every endpoint has auth middleware. Every data access checks ownership.
Input Every user input has a Zod schema or equivalent validation.
Queries No string interpolation in SQL. Parameterized queries only.
Secrets No hardcoded values. No fallbacks for sensitive env vars.
Errors Error responses return generic messages. Details logged server-side only.
CORS Explicit origin allowlist. No wildcards in production config.
Headers Security headers set (CSP, X-Frame-Options, etc.).
Dependencies New packages checked for known vulnerabilities.

Automate What You Can

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-recommend
npx secretlint --init

# Run the configured scanner in CI:
npx secretlint "src/**/*.ts"

# Check for known vulnerabilities in dependencies
npm 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]

Code scanning supported patterns Security tests failure cases Human review application context
Figure 2. Scanners, tests and review provide different evidence about a change.

The Bottom Line

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.

Sources

  1. [1]Do Users Write More Insecure Code with AI Assistants? · Neil Perry, Megha Srivastava, Deepak Kumar and Dan Boneh
  2. [2]SQL Injection Prevention - OWASP Cheat Sheet Series · OWASP Cheat Sheet Series
  3. [3]cors middleware · Express.js · Express
  4. [4]Input Validation - OWASP Cheat Sheet Series · OWASP Cheat Sheet Series
  5. [5]GitHub - secretlint/secretlint: Pluggable linting tool to prevent committing credential. · Secretlint maintainers
  6. [6]Code scanning - GitHub Docs · GitHub Docs

Checked against these sources on

Related Articles