AI-Generated Code Security Risks: 7 Risks to Know in 2026
AI-generated code repeats familiar flaws at higher volume, plus one new risk: packages that don't exist. See the 7 risks studies measured and how to catch them.

Table of contents
- Key Takeaways About AI-Generated Code Security Risks
- Why AI-Generated Code Creates New Security Risks
- Insecure Code and Vulnerability Introduction
- Vulnerable and Hallucinated Dependencies
- Secrets and Sensitive Data Exposure
- Insecure Authentication and Authorization Logic
- Missing Security Context in AI-Generated Code
- Vulnerabilities That Bypass Traditional Code Review
- How to Reduce AI-Generated Code Security Risks
- FAQs
AI-Generated Code Security Risks: 7 Risks to Know in 2026
AI coding assistants write code faster than most review queues can absorb, but that speed has a measurable cost. AI-generated code security risks fall into seven classes, and peer-reviewed research has measured most of them. This guide maps each risk to what studies found and the control that catches it.
In short, AI-generated code mostly repeats vulnerability classes your team already knows: injection, weak credential storage, path traversal, and missing authorization. What changes is the volume, the misplaced confidence of the developer who accepts it, and one genuinely new class: packages that don't exist.
Key Takeaways About AI-Generated Code Security Risks
- Most security vulnerabilities in AI-generated code are familiar weakness classes. The new pressure comes from how many suggestions land per day and how rarely anyone traces where each line came from.
- Developers using an AI assistant in a controlled study wrote less secure code and rated it as more secure, so confidence is a risk signal in its own right.
- Package hallucination is the one class with no human equivalent. A model can import a dependency that was never published, and an attacker can register it first.
- Older study rates don't transfer to 2026 models. The weakness classes do, which is why controls should key on classes rather than on any one model's error rate.
Why AI-Generated Code Creates New Security Risks
A code model predicts the most likely next lines based on its training data. Pearce et al. explain that the model "will not necessarily generate the best code" but the completion "that best matches the code that came before." Public code contains insecure patterns, so the model learns them too. For background on how these assistants produce output, see this explainer on AI-generated code in development.
Human developers write the same bugs, so the difference lies in three traits. Volume: suggestions arrive faster than reviewers can read them. Confidence: the developer accepting a suggestion often trusts it more than code they wrote themselves. And hallucination: a model can reference a package or API that doesn't exist. Those traits shape each AI-generated code security risk in the catalog below.
The security risks of AI-generated code are best judged on evidence, so be honest about its age. The studies below tested models from 2021 to 2024. Their rates describe those models, not today's. What still holds is that the same classes keep appearing, and no single AI-generated code security vulnerabilities study covers all seven. The table names the closest evidence for each risk and says where none exists:
Insecure Code and Vulnerability Introduction
Risk 1 is the plainest one: the model writes a known vulnerability class into otherwise working code. Pearce et al. prompted the August 2021 Copilot technical preview with 89 scenarios built around high-risk weaknesses, many drawn from MITRE's Top 25 list. Of 1,689 programs, they found about 40% vulnerable. That was an early model, and the rate in that study shouldn't be read as a 2026 figure.
The per-class results are more useful in review than the headline rate. In the insufficiently protected credentials scenarios, the top-ranked suggestion was vulnerable in all three, and in two of them 17 or more of 20 suggestions were. Every top suggestion in the path traversal scenarios was vulnerable as well. Here's how the credential class tends to look in review (illustrative diff):
+ import hashlib
+
+ def hash_password(password: str) -> str:
+ return hashlib.md5(password.encode()).hexdigest()
It runs, it passes a unit test, and it stores passwords with a fast, unsalted hash. The cause is frequency: older tutorials and repositories use this pattern often. The control is static analysis on every AI-assisted change, with rules for weak hashing and other common application vulnerability types. Pearce et al. used CodeQL for most of their own detection.
Vulnerable and Hallucinated Dependencies
Risk 2 is the known-vulnerable package. A model learns which libraries and versions were popular when its training data was collected. It can then suggest a version that has since received a published vulnerability. No study in this article isolates that rate, and you shouldn't trust anyone who quotes one without a method. The cause is structural: training data has a cutoff, and advisories keep arriving.
Risk 3 is new. Spracklen et al. generated 576,000 code samples with 16 models and found average package hallucination rates of "at least 5.2% for commercial models and 21.7% for open-source models." They logged 205,474 unique hallucinated package names. In review, it looks harmless:
+ from flask_jwt_session_guard import require_session
Suppose the reviewer checks the registry and finds no such project. An attacker who registers that name first could get code execution in any environment that installs it. Researchers call this "package confusion"; it's also known as slopsquatting. The controls are SCA for known-vulnerable software dependency versions, plus a CI check that every new package exists, has history, and sits on an approved list. Spracklen et al. also tested mitigation strategies and found they "significantly reduce the number of package hallucinations," so the problem is tractable. For wider ecosystem exposure, see open-source software risks.
Secrets and Sensitive Data Exposure
Risk 4 covers two paths for sensitive data. The first is memorization. Huang et al. (FSE 2024) built prompts from public GitHub files that contained credentials and tested commercial tools, open-source models, and chatbots. The tools returned training data verbatim, and the researchers confirmed that two of the leaked credentials were valid when tested.
The second path is more common in review: generated code that writes sensitive data where it doesn't belong. In Pearce et al., one sensitive-information exposure scenario produced 10 vulnerable suggestions out of 12. A typical diff looks like this:
@app.post("/api/payments")
def create_payment():
+ logger.info(f"Incoming request: {request.json}")
The request body carries a card token and a bearer token, and now both sit in plaintext logs. Attackers read logs, chat exports, and tickets as well as repositories, as this breakdown of how attackers harvest secrets shows. The controls are secrets scanning that reaches beyond source code, and logging that writes only allow-listed fields.
Insecure Authentication and Authorization Logic
Risk 5 is access control that looks finished but isn't. The evidence here cuts against the obvious story. When Pearce et al. asked Copilot for handlers that required authentication, such as an admin-only page or a password-verified email change, it "did well." The model handles authentication when the prompt names it. The failures show up where nobody asks: object-level authorization.
+ @app.get("/api/invoices/{invoice_id}")
+ def get_invoice(invoice_id: int, user=Depends(current_user)):
+ return db.query(Invoice).filter(Invoice.id == invoice_id).first()
The endpoint checks that a user is logged in. It never checks that the invoice belongs to that user's tenant, so changing the ID returns another customer's record. That's an insecure direct object reference, and none of the studies here measured its rate in generated code. That gap is worth admitting rather than filling with a guess. The fix is one filter on tenant_id. The control is an authorization test per endpoint (user A requests user B's object and expects a 403), plus a review checklist for authentication bypass vulnerabilities.
Missing Security Context in AI-Generated Code
Risk 6 is the context-blind suggestion. The model sees the open file and the prompt. It doesn't see your threat model, your data classification, or the business rule that says refunds above a limit need a second approver. Code can be correct against the prompt and still wrong for the system.
Perry et al. captured this in a path-restriction task: return a file only if it sits inside /safedir. AI outputs often checked that the path started with /safedir but didn't canonicalize it, so .. sequences and symlinks still escaped. Only 12% of AI-assisted participants wrote a secure solution, against 29% of the control group. The authors noted that the assistant "does not have information about the structure of file paths or symlinks."
That's the same gap behind business logic vulnerabilities. The control is to write security requirements into the ticket and the prompt, then have reviewers check the diff against those business rules.
Vulnerabilities That Bypass Traditional Code Review
Risk 7 is the one that makes the other six worse. Perry et al. ran a user study with 47 participants: 33 with an AI assistant built on codex-davinci-002 and 14 without. Participants with the assistant "wrote significantly less secure code than those without access." They were also "more likely to believe they wrote secure code."
The SQL task shows the scale in that study. Of the AI-assisted participants, 36% wrote code vulnerable to SQL injection, against 7% of the control group. The assistant often built queries by string concatenation, and participants copied it. Participants who trusted the AI less and reworked their prompts produced code with fewer vulnerabilities.
Code review assumes the author understands the change and can defend it. With generated code, the author may only have accepted it, and the diff looks idiomatic. Code review best practices still apply, but review can't be the only gate. An analysis of ungoverned AI-generated code traces what fails first when it is, from visibility to ownership.
How to Reduce AI-Generated Code Security Risks
Each control below maps to one risk from the catalog. Together they turn a list of AI-generated code security vulnerabilities, risks, and owners into a review and pipeline checklist:
- Scan every AI-assisted change with SAST (Risk 1): Run static analysis in the IDE and again in CI. Weak hashing, injection, and path traversal are rule-detectable classes.
- Enforce a dependency version policy with SCA (Risk 2): Block new packages with known advisories at pull request time. A suggestion from an old training snapshot shouldn't reach the main branch.
- Verify every new package exists and is approved (Risk 3): Fail the build when a dependency is missing from the registry, newly published, or off the allow list. That's the check that catches hallucinated names.
- Scan for secrets beyond the repository (Risk 4): Cover logs, tickets, and chat, and restrict logging to allow-listed fields. Revoke and rotate anything that leaks.
- Test authorization on every generated endpoint (Risk 5): Add a cross-tenant test per route that touches an object ID. A missing ownership check then fails in CI before it reaches production.
- Give the model and the reviewer the missing context (Risk 6): Put security requirements in tickets, prompts, and repository instructions. Reviewers can then check the diff against written rules.
- Label AI-assisted pull requests and route them by risk (Risk 7): Treat the label as routing metadata. Changes touching auth, payments, or file access go to a security reviewer.
These controls overlap with guardrails for coding agents and with assistant configuration, but they're tied to the code itself. That keeps them valid whichever assistant your developers use next quarter.
Legit Security extends these controls to the moment code is generated. Legit VibeGuard runs SAST and SCA scans on AI-generated code, flagging injection flaws and dependency risks before commit, and restricts which files assistants can read so credential stores stay out of AI context. AppSec teams get centralized visibility across AI-generated code. See how it works on the AI-generated code security page, or book a demo.
Frequently Asked Questions
Is AI-generated code less secure than human-written code?
In Perry et al.'s controlled study, yes, on four of five security tasks. The scope matters: 47 participants, two-thirds of them undergraduates, using a 2022-era Codex model under a two-hour limit. The finding measures developers working with an assistant, including their choices about what to accept, and the model it used has since been superseded.
What is package hallucination, and how do attackers exploit it?
Package hallucination happens when a model imports or recommends a dependency that was never published. An attacker can watch for names that models suggest, register them on public registries, and add a malicious install script. The next developer who accepts the suggestion and runs the install command can then execute the attacker's code, often on a laptop with access to source and credentials.
Do newer AI models still produce insecure code?
Newer models may perform better, but no study cited here measures 2026 models, so any current rate would be a guess. What the evidence supports is persistence: Spracklen et al., in a 2025 paper, described package hallucination as "a persistent and systemic phenomenon." Plan controls around weakness classes rather than waiting for a model that never makes them.
Should AI-generated code be labeled in pull requests?
Yes, when the label drives a decision. A label can trigger stricter scanning, require tests, or route sensitive paths to a security reviewer. It also lets you measure where generated code concentrates and which classes recur. Labels that only satisfy policy, with no routing behind them, add friction without reducing risk.
Can SAST tools catch AI-generated code security vulnerabilities?
SAST catches many of them, because most are familiar classes such as injection and path traversal. Pearce et al. relied on CodeQL for most of their detection. But the authors had to review several scenarios manually, including the authentication and credential-protection ones, because those depended on context a rule couldn't see. Pair SAST with authorization tests and human review.
Who's accountable for a vulnerability an AI assistant wrote?
The developer who merged it and the team that owns the service, just as with any other code. An assistant can't own a fix, answer an incident ticket, or be paged. Treat generated code as code the merging engineer chose to ship, and make sure ownership records name a person.
References (APA 7th edition)
Huang, Y., Li, Y., Wu, W., Zhang, J., & Lyu, M. R. (2024). Your code secret belongs to me: Neural code completion tools can memorize hard-coded credentials. Proceedings of the ACM on Software Engineering, 1(FSE), Article 111. https://doi.org/10.1145/3660818
Pearce, H., Ahmad, B., Tan, B., Dolan-Gavitt, B., & Karri, R. (2022). Asleep at the keyboard? Assessing the security of GitHub Copilot's code contributions. In 2022 IEEE Symposium on Security and Privacy (SP). https://doi.org/10.1109/SP46214.2022.9833571
Perry, N., Srivastava, M., Kumar, D., & Boneh, D. (2023). Do users write more insecure code with AI assistants? In Proceedings of the 2023 ACM SIGSAC Conference on Computer and Communications Security (pp. 2785–2799). https://doi.org/10.1145/3576915.3623157
Spracklen, J., Wijewickrama, R., Sakib, A. H. M. N., Maiti, A., Viswanath, B., & Jadliwala, M. (2025). We have a package for you! A comprehensive analysis of package hallucinations by code generating LLMs. In 34th USENIX Security Symposium (USENIX Security 25) (pp. 3687–3706). https://www.usenix.org/conference/usenixsecurity25/presentation/spracklen
Cite this article: Legit Security. (2026, October 16). AI-generated code security risks: 7 risks to know in 2026. Legit Security. https://www.legitsecurity.com/guides/ai-generated-code-security-risks
Legit Security needs the contact information you provide to us to contact you about our products and services. You may unsubscribe from these communications at any time. For information on how to unsubscribe, as well as our privacy practices and commitment to protecting your privacy, check out our Privacy Policy.
More Articles

AI Agent Supply Chain Security: Securing Agentic Development
AI agents install packages, MCP servers and skills with developer credentials. Learn how to inventory, pin and verify every component they pull in.



See it in your stack
Every prompt, every commit, every deploy, covered the moment you're ready.


