Skip to main content

The OWASP Top 10 in AI-generated code

AI-generated code fails security review in predictable places. A walkthrough of the OWASP risks generators introduce most often — with the shape each one takes and how to catch it before merge.

Key Takeaways

  • Plausible Syntactic Completeness: AI generators write code that compiles and passes unit tests, yet quietly lacks authorization boundaries.
  • Top Failure Modes: Access control (CWE-284), SQL injection (CWE-89), and hardcoded secrets (CWE-798) appear in over 60% of flagged AI diffs.
  • Training Data Latency: Generative LLMs frequently reproduce deprecated cryptographic primitives and un-sanitized string interpolation patterns found in public repositories.
  • Automated Defense: Catch these vulnerabilities pre-commit using the CodePeel security scan engine.

OWASP vulnerabilities in AI-generated code are repeatable security anti-patterns introduced by large language models when synthesizing software without explicit security constraints.

Generative coding assistants—whether Claude Code, Cursor, Copilot, or Windsurf—solve prompts locally. If you ask for "an endpoint to fetch user invoices," the assistant writes working code that fetches records, but frequently omits the tenancy authorization check that verifies who owns the invoice.

This guide explores how the OWASP Top 10 manifests in AI-authored code, how to identify vulnerabilities during review, and how automated gates stop them before merging.

Why AI-generated code fails security differently

A critical secret-exposure finding from a live CodePeel review
A critical secret-exposure finding from a live review — hardcoded credentials flagged with a revoke recommendation.

Three behavioral traits make AI-generated code distinct from human development:

  1. Syntactical plausibility: The generated code formats beautifully, includes docstrings, and looks like senior-level production syntax. Human reviewers tend to skim it with lower skepticism.
  2. Local optimization blind spots: The model optimizes the immediate prompt request in isolation, unaware of surrounding multi-tenant boundaries or enterprise secret management policies.
  3. Historical training artifacts: Models trained on public GitHub repositories perpetuate outdated coding practices that were common a decade ago.

A01: Broken Access Control (CWE-284)

What the AI writes: The generator authenticates the user session, but forgets to authorize access to the requested entity ID:

// Vulnerable: Authenticates caller but never authorizes the entity lookup
app.get('/invoices/:id', requireAuth, async (req, res) => {
  const invoice = await invoices.findById(req.params.id);
  res.json(invoice);
});

This endpoint passes manual sanity checks, yet allows any authenticated caller to view any competitor's confidential invoice simply by modifying the URL parameter.

How to catch it: Enforce tenancy constraints directly in the database query. The user's account ID must be checked alongside the resource key:

// Secured: Query enforces tenancy boundary
app.get('/invoices/:id', requireAuth, async (req, res) => {
  const invoice = await invoices.findOne({
    _id: req.params.id,
    organizationId: req.user.organizationId
  });
  if (!invoice) return res.status(404).json({ error: 'Invoice not found' });
  res.json(invoice);
});

A02: Cryptographic Failures (CWE-327)

What the AI writes: Outdated or insecure cryptographic functions: MD5 or SHA-1 for password hashing, predictable random number generators for security tokens, or plaintext secret comparisons vulnerable to timing attacks.

How to catch it: Prohibit custom cryptographic implementations. Enforce modern standard libraries (crypto.timingSafeEqual, Argon2, bcrypt) and verify that tokens are generated via cryptographically secure pseudo-random number generators (crypto.randomBytes).

A03: Injection Flaws (CWE-89, CWE-79)

What the AI writes: Direct string interpolation inside database queries, shell scripts, or HTML templates:

// Vulnerable: SQL Injection via template literal
const users = await db.query(
  `SELECT * FROM users WHERE email = '${req.body.email}'`
);

Because prompts often demonstrate queries as raw string examples, language models frequently mirror that pattern rather than using parameterized inputs.

How to catch it: Enforce parameterized prepared queries across all database drivers:

// Secured: Parameterized statement isolates untrusted input
const users = await db.query(
  'SELECT * FROM users WHERE email = $1',
  [req.body.email]
);

Our OWASP security scanning engine flags SQL interpolation patterns automatically on every pull request.

A05: Security Misconfiguration (CWE-16)

What the AI writes: Permissive default settings designed to "make things work" on the first try:

  • Overly permissive CORS headers (Access-Control-Allow-Origin: *)
  • Debug modes and stack trace dumps left enabled in production routes
  • Storage buckets configured with public read access
  • Missing rate-limiting headers on authentication endpoints

How to catch it: Maintain standardized infrastructure-as-code linting and review all environment-specific configurations during PR review.

A07: Identification and Authentication Failures (CWE-287)

What the AI writes: Credential fallbacks that silently default to hardcoded strings when environment variables are missing (CWE-798):

// Vulnerable: Hardcoded fallback secret
const jwtSecret = process.env.JWT_SECRET || "fallback-secret-key-123";

How to catch it: Fail closed. When mandatory security configuration is absent, throw an immediate process exception:

// Secured: Fails closed on missing configuration
const jwtSecret = process.env.JWT_SECRET;
if (!jwtSecret) throw new Error('JWT_SECRET must be configured');

Summary of AI vulnerability risks

OWASP CategoryPrimary CWEAI Generation PatternAutomated Defense
A01: Broken Access ControlCWE-284Direct ID lookups without tenant filteringModel-driven SAST Review
A02: Cryptographic FailuresCWE-327Deprecated hashing algorithms (MD5/SHA1)Deterministic AST Linting
A03: Injection FlawsCWE-89Template literal SQL and shell executionDeterministic Regex + SAST
A05: MisconfigurationCWE-16Permissive CORS and verbose error leaksRepository Compliance Rules
A07: Auth FailuresCWE-798Hardcoded secret fallbacks (`

Stopping AI vulnerabilities before merge

Pair automated tools to create defense-in-depth:

  1. Run pre-commit checks in your editor via the CodePeel VS Code extension.
  2. Connect coding assistants via our Claude Code MCP server to inspect diffs in-flight.
  3. Enforce pre-merge quality gates to block vulnerable pull requests automatically.
  4. Benchmark your automated review coverage using our framework in How to Benchmark an AI Code Reviewer.

Related security guides