How to Catch Security Vulnerabilities in AI-Written Code
AI coding tools have made it possible to build apps, plugins and websites faster than ever. But speed has a hidden cost. Research from universities and security companies has repeatedly found that a meaningful share of AI-generated code contains security weaknesses, especially when developers accept suggestions without review. The security vulnerabilities in AI-written code are usually not exotic. They are the same classic mistakes that have caused data breaches for decades, just produced faster and with more confidence.
This guide explains the most common vulnerabilities AI coding assistants introduce, shows what they look like in plain English, and gives you a simple process to catch them before your code goes live. It is useful for developers, freelancers building client sites, and anyone “vibe coding” their first app.
Why AI Writes Insecure Code
AI models learn from huge amounts of public code. Much of that code is old, written for tutorials, or simply insecure. The AI reproduces common patterns, not necessarily safe ones. A few other factors make things worse:
- AI optimizes for “it works.” If your prompt asks for a login form, the AI focuses on making the form function, not on rate limiting, password hashing or session security.
- Missing context. The AI does not know your security requirements, your users, or which data is sensitive unless you tell it.
- Outdated knowledge. Models may suggest deprecated functions or library versions with known vulnerabilities.
- Human over-trust. Clean, well-commented code feels trustworthy, so people review it less carefully.
The 10 Most Common Security Vulnerabilities in AI-Written Code
1. SQL injection
This happens when user input is pasted directly into a database query. An attacker can type special characters into a form field and change the query to read, modify or delete your data. AI tools still sometimes build queries by joining strings together, especially in quick examples.
The fix: always use parameterized queries or prepared statements. In WordPress, use $wpdb->prepare(). In other frameworks, use the query builder or ORM properly.
2. Cross-site scripting (XSS)
XSS happens when user input is shown on a page without being escaped. An attacker can inject JavaScript that runs in other visitors’ browsers, stealing sessions or redirecting them. AI code often outputs variables directly into HTML.
The fix: escape all output based on context (HTML, attributes, URLs, JavaScript). WordPress has functions like esc_html(), esc_attr() and esc_url(). Modern frameworks like React escape by default, but watch for “dangerously set” HTML features.
3. Hardcoded secrets and API keys
AI often places API keys, passwords and tokens directly in the code to make an example work. If that code is committed to Git or pushed to a public repository, your keys can be found and abused within minutes.
The fix: store secrets in environment variables or a secrets manager, add .env files to .gitignore, and use secret-scanning tools. If a key has ever been committed, rotate it immediately. Our guide on AI coding assistants and wp-config.php security covers this for WordPress sites.
4. Missing input validation
AI-generated code often assumes inputs are well-behaved. It does not check that an email is actually an email, that a number is within a sensible range, or that a file upload is really an image.
The fix: validate every input on the server side, not just in the browser. Check type, length, format and allowed values. Reject anything unexpected.
5. Broken authentication and weak password handling
AI may suggest storing passwords with weak hashing (like MD5 or SHA-1), or even in plain text. It may skip rate limiting on login forms, making brute-force attacks easy, or create session tokens that never expire.
The fix: use your framework’s built-in authentication where possible. Hash passwords with modern algorithms like bcrypt or Argon2. Add rate limiting, account lockouts and two-factor authentication. See our two-factor authentication setup guide and our explanation of passkeys.
6. Missing authorization checks
Authentication checks who you are. Authorization checks what you are allowed to do. AI code frequently forgets the second part. For example, an “edit profile” endpoint that updates whatever user ID is sent, without checking that it belongs to the logged-in user.
The fix: check permissions on every sensitive action on the server. In WordPress, use current_user_can() and nonces for every form and AJAX request.
7. Insecure file uploads
Upload code from AI often trusts the file name and extension. Attackers can upload a script disguised as an image and then run it on your server.
The fix: check the real file type, limit allowed types and sizes, rename uploaded files, store them outside the web root where possible, and never allow executable files.
8. Vulnerable or fake dependencies
AI may suggest outdated packages with known vulnerabilities, or even invent package names that do not exist. Attackers watch for these “hallucinated” names and publish malicious packages under them, a trick sometimes called “slopsquatting.”
The fix: verify every package on the official registry, check maintenance and download history, pin versions, and run npm audit, pip-audit or a tool like Snyk or Dependabot.
9. Overly detailed error messages
AI code often prints full error messages, stack traces or database errors to the screen. These help attackers learn about your system.
The fix: show users a simple, friendly error, and log the technical details privately. Turn off debug mode on live sites.
10. Insecure defaults and configuration
Examples include CORS settings that allow any website to call your API, debug mode left on, permissive file permissions, or disabled SSL certificate checks “to make it work.”
The fix: review configuration changes carefully, use secure defaults, and never disable security checks to silence an error.
New Risks: AI Features Inside Your App
If the app you are building uses AI itself, such as a chatbot or an AI agent that reads emails or web pages, there are extra risks:
- Prompt injection: attackers hide instructions in content the AI reads, tricking it into leaking data or taking actions. Read our prompt injection guide for beginners.
- Over-permissioned agents: giving an AI agent access to delete files, send emails or make payments without human approval.
- Data leakage: sending private customer data to AI APIs without consent or proper settings.
For website chatbots specifically, our guide to adding an AI chatbot to WordPress without hurting trust covers safe setup.
Risks from the AI Coding Agent Itself
Modern AI coding agents do more than suggest code. They run terminal commands, install packages and edit many files at once. That creates new risks:
- An agent may run destructive commands, like deleting files or dropping database tables.
- It may read secret files like
.envorwp-config.phpand include them in its context. - It may follow malicious instructions hidden in a README, issue or web page it reads.
Keep agents in a sandbox or local environment, require approval for risky commands, and avoid running them directly on live servers. Our articles on auto-approve mode and AI agents on live WordPress sites go deeper.
How to Catch Vulnerabilities Before They Ship
- Prompt for security. Ask the AI explicitly: “Write this securely. Validate input, use parameterized queries, escape output, and do not hardcode secrets.” It helps more than you might think.
- Ask for a security review. After the code is written, ask the AI (or a different model) to review it for OWASP Top 10 issues and explain each risk.
- Run automated scanners. Tools like Semgrep, CodeQL, SonarQube and Snyk catch many common vulnerability patterns automatically.
- Scan for secrets. Use GitHub secret scanning, Gitleaks or TruffleHog before pushing code.
- Audit dependencies. Run your package manager’s audit tool and keep dependencies updated.
- Test it. Include security-focused test cases: unusual inputs, unauthorized users, oversized files. Our guide on how to test AI-generated code walks through a full process.
- Get a human review. For anything involving payments, logins or personal data, have an experienced developer review the code.
The OWASP Top 10 is a great free reference for the most important web security risks, and OWASP also publishes a Top 10 for LLM and generative AI applications for apps that use AI features.
Security Checklist for AI-Written Code
| Area | What to check |
|---|---|
| Input | All input validated and sanitized on the server |
| Database | Parameterized queries only |
| Output | All output escaped for its context |
| Secrets | No keys or passwords in code or Git history |
| Auth | Strong hashing, rate limiting, 2FA available |
| Permissions | Every sensitive action checks user permissions |
| Uploads | Real file type checked, size limited, no executables |
| Dependencies | Verified, maintained, audited |
| Errors | No stack traces or debug info shown to users |
| Config | Debug off, CORS restricted, secure defaults |
Is AI-Written Code Less Secure Than Human Code?
Not necessarily. Humans write insecure code too. The difference is volume and confidence. AI lets one person produce far more code in a day, and that code often looks polished, so it gets less scrutiny. The answer is the same discipline good teams already use: code review, automated scanning and testing. With those in place, AI-assisted code can be just as secure as code written by hand, and sometimes more so, because AI can also help you find bugs.
A Reusable Secure-Coding Prompt
Save this prompt and paste it at the start of any coding session. It will not make AI code perfect, but it noticeably reduces the most common mistakes:
“You are helping me write production code. Follow secure coding practices: validate and sanitize all user input on the server, use parameterized queries, escape all output for its context, never hardcode secrets (use environment variables), check user permissions on every sensitive action, use the framework’s built-in security functions, avoid deprecated functions, and only use well-known, maintained packages. After writing the code, list any security assumptions you made and any risks I should test.”
The last sentence is the most useful part. Asking the AI to list its assumptions often reveals gaps, like “I assumed the user is already logged in,” that you can then fix or test.
Frequently Asked Questions
Is AI-generated code safe?
It can be, but only after review and testing. AI-generated code often contains common vulnerabilities like missing input validation, SQL injection and hardcoded secrets.
What is the most common vulnerability in AI code?
Missing input validation and related injection issues (SQL injection and XSS) are among the most common, along with hardcoded secrets.
Can AI find security vulnerabilities?
Yes. AI is helpful for reviewing code and explaining risks, especially when combined with dedicated security scanners. It should support, not replace, proper review.
Which AI coding tool is most secure?
No tool is secure on its own. Security depends on how you prompt, review, test and deploy. Compare features in our guide to the best AI coding assistants, then apply the checklist above whichever you choose.
Final Thoughts
AI coding assistants are powerful, but they repeat the same security mistakes humans have made for years, just faster. Know the common vulnerabilities, prompt for secure code, scan everything automatically, test edge cases, and keep a human in the loop for sensitive features. Do that, and you get the speed of AI without handing attackers an easy way in.








3 Comments