The Hidden Security Risks of AI-Generated Code

Insecure patterns are only the visible risk. This article covers the quieter ones: invented package names, secrets, licence exposure, supply-chain drift and tests that share the code's blind spots, with what the evidence shows and where it stops.

When people discuss the security of AI-generated code, the conversation usually stops at "it sometimes writes vulnerable code." That is true, and it is the least interesting part. A vulnerable query is something a static analyser can often flag. The harder risks are the ones that do not look like a bug: a dependency that should not exist, a credential pasted into an example, a snippet whose licence nobody checked, and a test suite that confirms the code does exactly what it does.

This article walks through those risks one at a time. For each I say what the evidence supports, where it stops, and what a team can do about it defensively. I do not include exploit instructions. Where I describe how a weakness could be abused, I keep it at the level a defender needs.

As in the rest of this series, research here is mixed, and some points are my own analysis, which I label. Where I have no source, I say so instead of guessing at a number.

Why this matters now

Assistants no longer only complete a line. They propose dependencies, write configuration, generate tests and, in agentic setups, run commands. Each of those widens the set of things that can go wrong without a human noticing, because the output is fluent and the volume is high.

The practical consequence is that reviewing the diff is no longer enough. You also have to ask what the change pulled in, what it exposed, what it copied and what its tests actually prove. NIST's Secure Software Development Framework frames secure development as practices added across the lifecycle, grouped into preparing the organisation, protecting the software, producing well-secured software and responding to vulnerabilities 1. The risks below map onto those groups: some are about how we produce code, some about how we protect the supply chain and some about how we respond when the code is wrong.

Background: a risk map

RiskWhat goes wrongWhy it is easy to missPrimary control
Insecure patternsWeaknesses in generated logic or configurationCode looks idiomatic and passes happy-path testsStatic analysis, independent review, secure defaults
Hallucinated packagesA suggested dependency does not exist, or exists as someone else's registrationThe install either fails or silently succeedsDependency allowlists, registry checks, lockfiles
SecretsCredentials appear in code, examples or promptsExample values look like placeholders until they are notSecret scanning, vault-based access, short-lived credentials
Licence exposureGenerated code resembles existing code under a licence you must honourNo visible marker in the snippetSimilarity checks, policy, human review for large blocks
Supply-chain driftPinned, verified inputs are replaced by whatever the model proposedEach change is smallProvenance, SBOMs, signed artefacts, private registry
Inherited blind spotsTests and code share one misreadingEverything is greenIndependent test design, abuse cases

Risk 1: insecure patterns, and what the numbers can and cannot tell you

The first body of evidence is about code quality directly. A study of GitHub Copilot examined generated code across scenarios linked to well-known weakness categories and found about 40% of the programs vulnerable 2. That was one tool in 2021, on a fixed scenario set.

A later empirical study analysed 733 snippets attributed to three AI tools in public GitHub projects. It found weaknesses in 29.5% of Python snippets and 24.2% of JavaScript snippets, across 43 weakness categories, eight of them in the 2023 CWE Top 25, including insufficiently random values, code injection and cross-site scripting 3. A vendor report states that AI-generated code introduced risky flaws in 45% of its tests, across more than 100 models and four languages 4. I treat that one as indicative only: it is a vendor's own report, and the page I read gives limited method detail.

What I take from this, as analysis: these figures are not comparable with one another. They differ in tool, year, language and method. The defensible statement is that generated code regularly contains recognisable weakness classes and therefore needs the same scanning and review as any other code. Insufficiently random values are a good example of a pattern that reads as correct: the code runs, produces output that looks random and fails a security property nobody asked the test to check.

Two OWASP resources help here. Model output should be treated as untrusted input, with validation, context-appropriate encoding and parameterised queries applied downstream 5. And OWASP's Application Security Verification Standard, version 5.0.0, gives a checklist of requirements to verify against rather than relying on a feeling that the code looks right 6.

The dangerous code is not the code that looks wrong. It is the fluent code that passes every test somebody forgot to write.
Akarsh N

Risk 2: hallucinated and "slopsquatted" packages

Language models sometimes name libraries that do not exist. A large study of package hallucination analysed 16 code-generating models and 576,000 generated code samples across two programming languages. It reported average hallucination rates of at least 5.2% for commercial models and 21.7% for open-source models, and it found 205,474 unique hallucinated package names 7.

Those are the findings. What follows is my analysis of why they matter. If a model keeps proposing the same non-existent name, then anyone can register that name on a public registry and wait. A developer who pastes the install command and does not look closely may then install code the attacker controls. The informal name for this pattern is "slopsquatting". I did not find the term used in the study I verified, and I am using it only as shorthand for the pattern, not attributing it to any source. I also have not verified any real-world case in which this happened, so I make no claim about prevalence.

What can a defender do without special tooling?

  1. Pin and lock. Limit dependencies to specific versions that were previously verified, and commit lockfiles so that an install reproduces what was reviewed. This is the guidance of OWASP's software supply chain cheat sheet 8.
  2. Gate new dependencies. Treat any package that appears in a change for the first time as a decision, not a side effect. The same cheat sheet suggests assessing suppliers by criteria such as active maintenance, maturity, number of maintainers and whether there is a vulnerability reporting process 8.
  3. Use a controlled source. The cheat sheet recommends a private artefact repository, with review before artefacts enter it, that cannot be bypassed 8. OWASP's guidance on vulnerable components also advises obtaining components only from official sources over secure links and preferring signed packages 9.
  4. Check existence and age before install. A package with no history, one maintainer and a name that exactly matches what a model suggested deserves a pause. This is my practical heuristic, not a requirement from a standard.
  5. Review the install step. Many teams review the import line but not the install command in a script or README.

I should be honest about a limit. The cheat sheet I read did not offer any guidance specific to typosquatting, so I am not claiming that pinning alone defeats it. Pinning prevents silent drift; it does not tell you the first version was trustworthy. That is what the verification and provenance steps are for.

Risk 3: secrets in generated code and in prompts

Hardcoded credentials are one of the oldest bad habits in software, and I have seen assistants reproduce them in sample code, configuration snippets and test fixtures. I do not have a verified study that quantifies how often AI tools emit real secrets, so I will not offer a rate. The risk has two directions.

Secrets going into code. Generated examples often include placeholder keys, and developers replace them with real ones during testing and then commit. This is not new, but speed raises the chance.

Secrets going into prompts. Pasting an environment file or log excerpt into a chat window sends that secret to a third party. Whether that is acceptable depends on your agreement and policy; the point is that it is a data-handling decision, not a convenience.

For scale, GitHub's blog states that more than 39 million secrets were leaked across GitHub in 2024, citing its State of the Octoverse 2024 report, and says push protection blocks secrets at commit time 10. That figure is GitHub's own statistic, quoted second-hand from its blog; I did not open the Octoverse report. It is not a measure of AI-caused leakage and I am not using it as one.

OWASP's Secrets Management Cheat Sheet is a good baseline: avoid secrets in source code, apply least-privilege access, rotate secrets and prefer short-lived ones so that a stolen credential works only briefly 11. In practice:

  1. Scan before merge. Turn on secret scanning and, where available, push protection so a credential is blocked at the moment of commit 10.
  2. Remove the need to paste. Give developers and agents access to secrets through a vault or an environment injected at runtime, not through files in the workspace.
  3. Make leaks cheap to recover from. Short-lived credentials and automated rotation turn a leak from an incident into a nuisance 11.
  4. Write the prompt rule down. A one-page rule on what may not be pasted into an assistant (credentials, customer data, private keys) is more useful than a policy nobody reads.

Risk 4: licence and provenance

Generated code may resemble existing code. An ICSE 2025 study of 14 popular models found that even the best-performing ones produced 0.88% to 2.01% of code that was strikingly similar to existing open-source implementations, and that most models failed to give accurate licence information, especially for code under copyleft licences 12.

Read that carefully. It says similarity was found at a low rate in the tested setup and that models are poor witnesses to the licence of what they produce. It does not say that any particular output infringes anything, and I am not giving legal advice. Whether a given snippet creates an obligation is a legal question that depends on the licence, the amount and the jurisdiction.

My analysis of the practical implication: the risk is concentrated in larger, distinctive blocks and in code that ends up in distributed products, so a proportionate control is to apply a similarity or software composition check to large generated additions and to ask your counsel which licences you cannot accept. Small boilerplate carries little risk by comparison. If you sell to regulated customers who ask for software bills of materials, you will also want a way to show where code came from.

Risk 5: supply-chain exposure beyond packages

The assistant itself is now part of your supply chain. OWASP's LLM supply chain entry covers risks in models, data and components and recommends vetting suppliers, using software bills of materials, verifying signatures and hashes, and keeping components patched 13. SLSA, a set of incrementally adoptable supply-chain security guidelines, is a useful way to reason about what you should require of the things you build and ship 16.

I would apply four questions to every AI tool in the delivery path:

  1. What can it read? Repositories, tickets, documentation and environment files may contain sensitive material or instructions written by someone untrusted.
  2. What can it change? Files, dependencies, pipelines, infrastructure.
  3. Who updates it? Models and extensions change under you; a behaviour you reviewed last quarter may not be today's behaviour.
  4. What evidence does it leave? If you cannot tell afterwards which changes it made, you cannot investigate an incident involving it.

Article 07 in this series covers agents specifically. For this article, the key point is that "we use an assistant" is a supplier relationship and should be managed like one.

Risk 6: tests that inherit the code's blind spots

This is the risk I think teams underestimate most, so I will spend longer on it.

A test suite proves that the behaviours it asserts are present. It cannot prove that other behaviours are absent. When an assistant writes the implementation and then writes the tests for it, both artefacts come from the same reading of the same prompt. If that reading missed a requirement, such as "a user may only fetch their own records", the code will not enforce it and the tests will not check it. The suite is green and the control is missing.

I have seen this pattern in reviews; I have no controlled study to cite, so I present it as a hypothesis grounded in mechanism. A related, better-evidenced point from the user study on assistants is that participants were more confident in code that was less secure 14. Together they suggest a dangerous combination: confidence from green tests, and tests that cannot fail in the interesting way.

Here is a defensive way to break the inheritance.

  1. Derive tests from requirements, not from the code. Write security requirements as sentences first: who may do what to which object. Then write tests from those sentences.
  2. Add abuse cases. For each externally reachable endpoint, include at least one test where the caller is authenticated but not authorised for the object.
  3. Separate authorship for high-risk code. For authentication, authorisation, payments and data handling, the person or tool writing tests should not be the one that wrote the implementation.
  4. Mutation-check the important controls. Remove or weaken the control on a branch and confirm that some test fails. If nothing fails, the test suite does not protect that control.
  5. Review the assertions, not the count. Coverage numbers say which lines ran, not which properties were checked.

The OWASP Top 10 2021 distinction between insecure design and insecure implementation is relevant here: no amount of generated testing repairs a design that omitted a control 15.

Real-world patterns (not incidents)

I am deliberately not citing named incidents because I did not verify any for this article. These are patterns I would expect a team to find by looking.

Industry gaps

Based on the evidence and my programme experience:

  1. No shared taxonomy for AI-specific code risks. Weakness lists exist for code and for LLM applications, but few teams map assistant behaviour to either.
  2. Little public evidence on real-world exploitation of hallucinated packages. The study measures how often names are invented 7; I did not find verified data on how often they are abused.
  3. Evidence on secrets leakage from assistants is thin. The statistics I could verify concern leaks in general, not leaks caused by AI tools 10.
  4. Licence tooling lags generation. The study shows models do not reliably report licences 12; most teams do not run similarity checks.
  5. Few teams audit their tests for independence. The inherited blind-spot risk is largely unmeasured.

Practical recommendations

For early-stage startups

  1. Turn on secret scanning with push protection and a dependency scanner in CI before anything else 10.
  2. Commit lockfiles and require review for any new dependency 8.
  3. Require a second human reviewer for authentication, authorisation, payment and data handling changes.
  4. Write three abuse-case tests for each externally reachable endpoint.

For scaling companies

  1. Add a private registry or allowlist for dependencies and block unreviewed packages in CI 8.
  2. Separate test authorship from code authorship in high-risk modules.
  3. Run a similarity or composition check on large generated additions.
  4. Record AI involvement in pull request metadata so you can sample it in audits.

For enterprises

  1. Extend SSDF-aligned evidence 1 to show which changes involved generation, how they were reviewed and by whom.
  2. Define permitted tools, data classes and approval paths, and review them as suppliers 13.
  3. Require provenance and signed artefacts for what you ship, using SLSA as a reference model 16.
  4. Include assistant tooling in third-party risk management.

Key takeaways

Conclusion

The hidden risks of AI-generated code are not exotic. They are the old problems of dependencies, secrets, provenance and test quality, arriving faster and wearing better-written clothes. That is both the bad news and the good news. The controls are mostly known: pinning, scanning, least privilege, provenance, independent testing and review in proportion to risk.

The work is to apply them to the new paths that code now takes into your product. If I had to choose a first week for a small team, it would be secret scanning, a dependency gate and three abuse-case tests for the endpoint that matters most. That does not solve everything. It does remove the cheapest ways to be wrong.

Views are my own; examples are composites and do not describe any specific employer or client.

Key takeaways

References

  1. NIST (CSRC). "Secure Software Development Framework (SSDF) Version 1.1: Recommendations for Mitigating the Risk of Software Vulnerabilities (NIST SP 800-218)." 2022-02. https://csrc.nist.gov/pubs/sp/800/218/final — Supports: SSDF adds secure practices to any SDLC, in four groups (PO, PS, PW, RV). Limitations: a practice framework, not specific to AI assistants.
  2. Pearce, Ahmad, Tan, Dolan-Gavitt, Karri (IEEE Symposium on Security and Privacy 2022; arXiv 2108.09293). "Asleep at the Keyboard? Assessing the Security of GitHub Copilot's Code Contributions." 2021-08. https://arxiv.org/abs/2108.09293 — Supports: about 40% of Copilot programs in security-relevant scenarios were vulnerable. Limitations: abstract only was read; one tool, 2021, defined scenarios.
  3. Fu, Liang, Tahir, Li, Shahin, Yu, Chen (ACM TOSEM, accepted; arXiv 2310.02059). "Security Weaknesses of Copilot-Generated Code in GitHub Projects: An Empirical Study." 2023-10 (v4 2025-02). https://arxiv.org/abs/2310.02059 — Supports: 733 snippets from three tools; 29.5% of Python and 24.2% of JavaScript snippets affected; 43 weakness categories, eight in the 2023 CWE Top 25. Limitations: abstract only was read; snippets attributed to AI tools in public projects.
  4. Veracode. "2025 GenAI Code Security Report." 2025. https://www.veracode.com/resources/analyst-reports/2025-genai-code-security-report/ — Supports: vendor page states AI-generated code introduced risky security flaws in 45% of tests, across over 100 models and four languages. Limitations: vendor report; landing page only, little methodological detail.
  5. OWASP Gen AI Security Project. "LLM05:2025 Improper Output Handling." n.d. (2025 edition). https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/ — Supports: model output should be treated as untrusted input; validate, encode for context, parameterise queries.
  6. OWASP. "OWASP Application Security Verification Standard (ASVS) 5.0.0." 2025-05-30. https://asvs.owasp.org/ — Supports: ASVS is the OWASP list of application security requirements; current stable release is 5.0.0.
  7. Spracklen, Wijewickrama, Sakib, Maiti, Viswanath, Jadliwala (USENIX Security 2025; arXiv 2406.10279). "We Have a Package for You! A Comprehensive Analysis of Package Hallucinations by Code Generating LLMs." 2024-06 (v3 2025-03). https://arxiv.org/abs/2406.10279 — Supports: 16 models, 576,000 samples, two languages; average hallucination at least 5.2% for commercial and 21.7% for open-source models; 205,474 unique hallucinated names. Limitations: abstract only was read; the exploitation scenario and the term "slopsquatting" are not taken from this source.
  8. OWASP Cheat Sheet Series. "Software Supply Chain Security Cheat Sheet." n.d. https://cheatsheetseries.owasp.org/cheatsheets/Software_Supply_Chain_Security_Cheat_Sheet.html — Supports: pin to previously verified versions using lockfiles; assess suppliers; use a private artefact repository that cannot be bypassed; verify signatures and provenance. Limitations: gives no typosquatting guidance.
  9. OWASP Top 10 project. "A06:2021 Vulnerable and Outdated Components." 2021 edition. https://top10.owasp.org/2021/A06_2021-Vulnerable_and_Outdated_Components — Supports: obtain components from official sources over secure links, prefer signed packages, inventory versions, monitor CVE sources. Limitations: 2021 edition.
  10. GitHub. "Next evolution of GitHub Advanced Security" (blog). n.d. https://github.blog/security/application-security/next-evolution-github-advanced-security/ — Supports: blog states more than 39 million secrets were leaked across GitHub in 2024 (citing the State of the Octoverse 2024), and describes push protection. Limitations: vendor blog; Octoverse report not opened; not a measure of AI-caused leakage.
  11. OWASP Cheat Sheet Series. "Secrets Management Cheat Sheet." n.d. https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html — Supports: least-privilege access, no hardcoded secrets, rotation, short-lived secrets.
  12. Xu, Gao, He, Zhou (ICSE 2025; arXiv 2408.02487). "LiCoEval: Evaluating LLMs on License Compliance in Code Generation." 2024-08 (v3 2025-02). https://arxiv.org/abs/2408.02487 — Supports: across 14 LLMs, 0.88% to 2.01% of code was strikingly similar to existing open-source code; most models gave inaccurate licence information, especially for copyleft. Limitations: abstract only was read; not legal analysis.
  13. OWASP Gen AI Security Project. "LLM03:2025 Supply Chain." n.d. (2025 edition). https://genai.owasp.org/llmrisk/llm032025-supply-chain/ — Supports: LLM supply chain vulnerabilities and mitigations including vetting suppliers, SBOM or AI BOM, signatures and hashes, patching.
  14. Perry, Srivastava, Kumar, Boneh (ACM CCS 2023; arXiv 2211.03622). "Do Users Write More Insecure Code with AI Assistants?" 2022-11. https://arxiv.org/abs/2211.03622 — Supports: participants with an AI assistant wrote less secure code and were more confident in it. Limitations: user study, 47 analysed participants.
  15. OWASP Top 10 project. "A04:2021 Insecure Design." 2021 edition. https://top10.owasp.org/2021/A04_2021-Insecure_Design — Supports: insecure design and insecure implementation are different; a flawed design cannot be repaired by perfect coding. Limitations: 2021 edition.
  16. SLSA (Linux Foundation / OpenSSF). "SLSA Specification (Supply-chain Levels for Software Artifacts), v1.2." n.d. https://slsa.dev/spec/v1.2/about — Supports: SLSA is a set of incrementally adoptable supply-chain security guidelines.