Dev tools

AI Generated Code Security: How to Review It

AI generated code security explained: the flaws AI tools commonly introduce, a real scan-and-fix example, and a step-by-step checklist for reviewing it.

By OmniAI Editorial · Nov 16, 2026 · 11 min read

AI generated code security has become a real concern now that tools like Copilot, Cursor, Claude Code, and Codex write a large share of new code. These assistants are fast and often impressive, but they can also introduce SQL injection, leaked API keys, missing permission checks, and dependencies that don't exist. The code looks clean and runs fine, which makes the problems easy to miss.

This guide explains why AI-written code has security gaps, which vulnerabilities show up most often, and how to review it properly. It includes a real example that we scanned and fixed, plus a checklist you can use on every pull request.

Is AI generated code safe?

So, is AI generated code safe? It's as safe as the review it gets. AI-written code isn't automatically worse than human code, and it often handles routine work well. But it has no understanding of your system's security needs, and it produces code faster than people can carefully read it.

Academic studies since 2021 have repeatedly found that AI coding assistants can suggest vulnerable code. One study from Stanford researchers also found that developers using an AI assistant tended to write less secure code while feeling more confident that it was secure. That combination of plausible-looking code and extra confidence is the real risk.

The practical answer: treat AI-generated code like code from a fast, talented new hire who doesn't know your codebase or your threat model. Use it, but review it.

Why AI-generated code has security problems

It learned from imperfect code

AI models are trained on huge amounts of public code, including outdated tutorials, old Stack Overflow answers, and insecure examples. They reproduce common patterns, and some common patterns are unsafe.

It optimizes for "it works"

When you ask for a feature, the AI aims to make it work. Security checks such as input validation, permission checks, and rate limits aren't part of "working" unless you ask for them, so they're often left out.

It doesn't know your context

The AI doesn't know which data is sensitive, who your users are, or which endpoints are public. It can't tell that a function it's editing is reachable from the internet, or that a field holds medical data.

It can invent packages: slopsquatting

AI models sometimes suggest software libraries that sound right but don't exist. Attackers have noticed. They register these made-up names on package registries like npm and PyPI and fill them with malicious code, waiting for someone to install the AI's suggestion. This attack is called slopsquatting.

A processor chip with two arrows leading to two identical package boxes, one of which carries a small orange mark.
Slopsquatting: an AI suggests a package name that sounds real, and an attacker has published a malicious package under that exact name.

Coding agents add new risks

Agents don't just suggest code; they run commands, install packages, and edit many files at once. They can also be manipulated. Instructions hidden in a README, an issue, a web page, or a project's rules file can steer an agent into doing something harmful, an attack known as prompt injection.

Fast, unreviewed AI coding is often called vibe coding. It's fine for throwaway experiments, but it's where most of these security problems slip through.

The most common vulnerabilities in AI-generated code

These are the problems reviewers find again and again in AI-written code.

Injection flaws

The AI builds a database query or shell command by pasting user input straight into a string. This opens the door to SQL injection and command injection, which let attackers read data or run commands on your server.

Hardcoded secrets

API keys, passwords, and tokens written directly into the code, often as "placeholders" that end up committed and pushed to a shared repository.

Missing authentication and authorization

Endpoints that don't check who is calling, or that check login but not permission. A common example: any logged-in user can view any other user's records by changing an ID in the URL.

Weak validation and unsafe file handling

Missing checks on input size, type, or format, and file paths built from user input, which allow attackers to read files outside the intended folder.

Insecure defaults and configuration

Debug mode left on, CORS opened to every site, verbose error messages that reveal internals, or cookies without security flags.

Weak cryptography and randomness

Outdated hashing for passwords, home-made encryption, or ordinary random number generators used for security tokens.

Risky dependencies

Packages that are outdated with known vulnerabilities, abandoned, or made up entirely.

AI generated code security in practice: a real example

Here's a small piece of Python code with typical AI-generated problems: a hardcoded key, a database query built from user input, and a shell command with user input inside it.

import sqlite3
import subprocess

API_KEY = "sk-live-1234567890abcdef"

def get_user(username):
    conn = sqlite3.connect("app.db")
    query = f"SELECT * FROM users WHERE name = '{username}'"
    return conn.execute(query).fetchall()

def ping(host):
    return subprocess.run(f"ping -c 1 {host}", shell=True, capture_output=True)

We ran two free scanners on it. Bandit, a Python security scanner, flagged the SQL query as a possible SQL injection and the shell=True call as a high-severity issue. But Bandit did not flag the hardcoded API key. A secret scanner, detect-secrets, caught the key straight away.

That's the first lesson: no single tool catches everything, so use more than one.

Here's the fixed version:

import os
import sqlite3
import subprocess

API_KEY = os.environ["API_KEY"]

def get_user(username):
    conn = sqlite3.connect("app.db")
    query = "SELECT * FROM users WHERE name = ?"
    return conn.execute(query, (username,)).fetchall()

def ping(host):
    return subprocess.run(["ping", "-c", "1", host], capture_output=True)

The key now comes from an environment variable. The query uses a parameter, so user input can't change the SQL. The command is passed as a list without a shell, so input can't inject extra commands.

On the fixed code, the secret scanner found nothing, and Bandit's medium- and high-severity findings were gone. Bandit still showed a few low-severity notes about using subprocess. That's the second lesson: tools point at places to look, and a person still has to judge them. Here, a reviewer should also ask whether host is validated before it's used.

How to review AI-generated code, step by step

The best defense is layers. Automated tools catch the obvious problems quickly, people catch what tools miss, and tests prove the code behaves correctly when things go wrong.

Small squares falling through three dashed horizontal layers, with a different square caught at each layer and one caught square shown in orange.
Layered review: each layer catches problems the others miss, so fewer reach production.

Step 1: Run automated scanners on every change

Set these up in your continuous integration (CI) pipeline, so they run on every pull request:

  • Static analysis (SAST): Semgrep (many languages), Bandit (Python), or GitHub's CodeQL scan code for risky patterns.
  • Secret scanning: Gitleaks, TruffleHog, or detect-secrets catch keys and passwords before they're committed or merged.
  • Dependency scanning: npm audit, pip-audit, OSV-Scanner, or Dependabot flag packages with known vulnerabilities.

All of these have free options.

Step 2: Check every new dependency

Before installing anything the AI suggests, confirm that the package exists, that its name is spelled exactly right, and that it's widely used and maintained. Look at the package page, the source repository, the download history, and the publish date. Be very wary of a package created recently with almost no history.

Step 3: Focus human review on high-risk code

You can't read every line with the same care, so prioritize:

  • Login, sessions, and permissions.
  • Anything that touches payments or personal data.
  • Database queries, file access, and shell commands.
  • Code that handles uploads or user input from outside.
  • Configuration and infrastructure files.

Keep AI-generated changes small enough to review. A 2,000-line pull request will get skimmed; a 200-line one will get read.

Step 4: Test the bad paths

AI-written tests usually check that things work. Add tests that check how things fail: empty input, very long input, special characters, wrong user, expired session, missing permissions. Ask the AI to write these tests too, then read them.

Step 5: Use AI code review as an extra layer

AI code review tools can scan a pull request for security issues, and they're good at spotting patterns like missing validation or injection risks. You can also ask your coding assistant directly: "Review this change for security vulnerabilities, and explain each one."

Treat AI review as a helpful second opinion, not a replacement. It can miss problems and occasionally invent ones that don't exist, and it shares the same blind spots as the AI that wrote the code.

Step 6: Protect the pipeline

Require pull requests and passing checks before code can merge into your main branch. Make sure at least one person approves changes to sensitive areas. This keeps a fast AI from becoming a fast route to production.

Secure code review checklist for AI-generated code

Use this secure code review checklist on every AI-assisted pull request that touches real users or data.

A clipboard with five checkbox rows, four of them ticked and one tick shown in orange.
A short checklist turns security review from a vague worry into a repeatable habit.

Input and output

  • Is all outside input validated for type, length, and format?
  • Are database queries parameterized, never built from strings?
  • Are shell commands avoided, or run without a shell and with fixed arguments?
  • Is output escaped correctly where it's shown in a web page?

Access control

  • Does every endpoint check who the user is and whether they're allowed to do this?
  • Can a user reach someone else's data by changing an ID?

Secrets and configuration

  • Are there any keys, tokens, or passwords in the code or config files?
  • Are debug mode, open CORS, and detailed error messages turned off in production?

Dependencies

  • Does every new package exist, with the exact correct name?
  • Is it maintained, widely used, and free of known vulnerabilities?

Data and crypto

  • Are passwords hashed with a modern algorithm built for passwords?
  • Are security tokens generated with a secure random generator?
  • Is sensitive data kept out of logs?

Behavior

  • Are there tests for invalid input and unauthorized access?
  • Do the automated scanners pass, and has someone judged their warnings?

Habits that improve AI generated code security

Review catches problems; good habits prevent them.

Ask for security up front. Say "use parameterized queries, validate all inputs, and read secrets from environment variables" in your prompt. The AI follows instructions it's given.

Put rules in your project instructions. Coding agents read files like CLAUDE.md or AGENTS.md. Add your security rules there once, so every session follows them.

Keep agents on a short leash. Run coding agents with permission prompts on, ideally in a sandbox or container. Don't give them production credentials. Our Claude Code beginner's guide explains how its permission modes work.

Be careful with untrusted content. Don't point an agent at unknown repositories, issues, or web pages and let it act unsupervised. They can carry hidden instructions.

Own the code. Whoever merges AI-generated code is responsible for it, exactly as if they had written it themselves.

FAQ

Is AI-generated code safe to use in production?

Yes, if it goes through the same review, testing, and scanning as human code. The danger isn't AI code itself but merging it without review. Higher-risk areas such as login, payments, and personal data deserve extra human attention.

Can AI review code for security vulnerabilities?

Yes, and it's a useful extra layer. AI code review tools catch many common issues quickly. But they can miss problems and report false ones, so combine them with traditional scanners and human review.

What is slopsquatting?

Slopsquatting is an attack where criminals publish malicious packages under names that AI models tend to invent. When a developer installs the package the AI suggested without checking, they install the attacker's code.

What tools can scan AI-generated code?

The same tools that scan any code: static analyzers like Semgrep, Bandit, and CodeQL; secret scanners like Gitleaks, TruffleHog, and detect-secrets; and dependency scanners like npm audit, pip-audit, OSV-Scanner, and Dependabot. Most have free versions.

Who is responsible for security flaws in AI-generated code?

The people and organization that ship it. AI tools don't take responsibility for the code they write. Treat AI output like any contribution: someone must review it, approve it, and own it once it's merged.

All articles

Read next

Language

EnglishEnglish · en TürkçeTurkish · tr DeutschGerman · de العربيةArabic · ar

Account

Enter your email. We’ll send you a sign-in link and a 6-digit code. No password needed.

Sign in

Theme

Language

Show our email address

To keep spam out of our inbox, please confirm your own email first. We will send you a 6-digit code.

We send codes only to these providers: gmail.com, googlemail.com, outlook.com, hotmail.com, live.com, msn.com, proton.me, protonmail.com, pm.me, icloud.com, me.com, mac.com, yahoo.com, aol.com, gmx.de, gmx.net, web.de, t-online.de, yandex.com, omniai.blog