AI Coding Assistant Hallucinations: Security Risks and Guardrails
AI coding assistant hallucinations are confident but incorrect suggestions, such as invented package names, unsafe authentication code, or outdated security settings. Because generated code can look polished and compile, teams should verify dependencies, check security-sensitive logic, and automate review before trusting it in a build or production system.
I’m Ermenildo Castro, a Filipino engineer in Seattle. In my work on software teams, the most troubling AI suggestions have not looked bizarre. They have looked ordinary: a neat import, a reasonable-sounding explanation, and one small detail that nobody checked. That is the trap. A fluent answer can persuade a tired reviewer to skip the very question that matters: does this package or security pattern actually exist, and is it safe now?
AI assistants can save time on routine tasks, but speed is not proof. This article looks at how hallucinations enter code, why they create real security risks, and what teams can put in place to catch them without banning useful tools. The aim is simple: keep the productivity, lose the blind trust.
What Are AI Coding Assistant Hallucinations?
An AI coding hallucination is output that appears factual or usable but contains something made up, mistaken, or unsupported. A model may invent a library, cite a function that does not exist, or suggest a security practice that no longer meets current guidance. The term does not mean the software is thinking or trying to deceive anyone. It means the answer is wrong while sounding sure.
Most code-generating models predict likely next pieces of text from patterns in their training data and the prompt. They do not automatically check whether a package is published today, whether a function is present in the latest SDK, or whether a security recommendation matches your system. If information is missing, the model may still produce a plausible continuation. The result can resemble code a skilled developer would write.
That resemblance matters. In prose, a strange fact may stand out. In code, an invented import can follow familiar naming rules, use sensible variable names, and sit inside a clean example. A reviewer may see valid syntax and assume the underlying details are real. A successful compile is not a full safety check, either: code may compile while still using a weak password flow or granting broad permissions.
I remember reviewing a generated setup example that looked routine at first glance. The commands were tidy, and the explanation fit the project. The useful habit was to stop at the unfamiliar dependency and verify it against the actual package registry and project documentation. That small pause changed the review from “looks fine” to “we know what we are installing.” Frankly, that is less exciting than a clever prompt, but far more useful.
Hallucinations can affect different parts of a project. An assistant might suggest a package that does not exist, use a real package with the wrong version or API, or recommend unsafe configuration. It may also give incorrect advice about encryption, identity, cloud access, logging, or error handling. The answer can mix correct and incorrect details, so checking one good part does not validate the rest.
The research on package hallucinations in code-generating models found frequent fabricated package suggestions in the study’s tests. Its results are evidence of a risk under those test conditions, not a guarantee that every assistant or every request will produce the same rate. The OWASP guidance on misinformation also identifies inaccurate model output as a risk that needs verification and human oversight.

Core Benefits and Importance
AI coding assistants can be useful. They can draft routine code, explain an unfamiliar error, suggest test cases, and help developers move through repetitive tasks. Used well, they can free a team to spend more time on design, code review, and the needs of the people who use the software. The goal is not to reject every suggestion; it is to put the right checks around suggestions that can cause harm.
Here is why the security side deserves attention:
- Package suggestions can affect the software supply chain. A dependency is not just a line of code. Installing it may bring in scripts, transitive dependencies, and permissions available to the build process. If a made-up name is later registered by an attacker, a developer who installs it may run code they never intended to trust.
- Security advice can age badly. Models may repeat patterns found in older examples. An authentication flow that was once common may no longer be the best choice for accounts that need strong protection. Teams should check current standards instead of treating old snippets as policy.
- The error can be subtle. An over-permissioned cloud policy or weak cryptographic choice may pass a basic build. It often takes someone who understands the security goal to notice the problem.
- AI increases the volume of suggestions. A developer can receive many snippets in a short time. Human attention is limited, so important checks need to be built into tools and workflows, not left to memory.
- Trust affects people beyond the engineering team. A weak login flow or compromised dependency can expose customer data, interrupt service, and create real costs for users. Good engineering includes stewardship: taking reasonable care of the systems and information entrusted to a team.
The supply-chain concern has a name: slopsquatting. It describes an attack in which someone registers a package name that AI tools have hallucinated, hoping a developer will later install the package after receiving that suggestion. It resembles typosquatting, where an attacker exploits a spelling mistake, but the risky name may be a model’s invention rather than a user’s typo.
In the paper’s tested prompts and models, researchers reported that about one in five recommended dependencies pointed to packages that did not exist, and their test set produced more than 205,000 unique fabricated package names. Those numbers should be read carefully: they describe the study, not a universal rate for every model, language, task, or software team. Still, a low chance can matter when the same suggestion appears repeatedly or is copied into a widely used tutorial.
That repeatability can make the attack more practical. If a model keeps producing the same invented name, an attacker may be able to register that name and wait for an installation. The risk grows when developers copy commands without checking the publisher, package history, source repository, or registry details. A single suggestion is not proof of an attack, but it is a reason to verify.
Authentication creates a separate risk. Ask a model to build a login flow and it may offer familiar but weak approaches, such as treating SMS codes as the strongest option for every account. For accounts that need better protection, current guidance favors phishing-resistant methods. Passkeys and other phishing-resistant authenticators can help protect users from fake login pages; they are not a magic shield, and teams still need a sound recovery process. See NIST’s digital identity guidance and CISA’s guidance on phishing-resistant MFA before setting policy.
The same caution applies to cryptography and cloud settings. A code block can name an old cipher, skip certificate checks, or grant broad access because the example is easier to write that way. The danger is not that an assistant is always wrong. It is that a plausible answer can travel from a chat window into a real system before anyone asks what it can access.
Step-by-Step Guide to Safer AI-Assisted Coding
Good guardrails fit the development process. They do not depend on every engineer remembering every warning while under deadline. Use the following steps to make checks routine.
- Set clear rules for sensitive work. Decide which tasks may use an assistant and which require extra review. Authentication, cryptography, authorization, payment handling, secrets, and cloud access deserve tighter rules than a simple test fixture. Write down what “extra review” means, so it is not just a vague request to be careful.
- Verify every new dependency. Before installing a suggested package, search the official registry and the project’s documentation. Check the exact name, publisher, release history, source repository, and whether the package is maintained. Look for signs that the name is a close match to a popular library. A package existing is only the first check; it does not prove that it is safe or appropriate.
- Use an approved dependency path. Maintain allowlists or an internal package catalog for high-risk environments. Require a reviewed change when a project adds or updates a dependency. Pin versions and commit lockfiles so builds use known dependency versions instead of silently changing on the next install. Review transitive packages too, because a direct dependency can bring other code along with it.
- Run automated checks before merging. Use software composition analysis to flag vulnerable or unapproved dependencies. Add checks that compare imports against known packages and flag unknown names for review. Run static analysis, secret scanning, and policy checks on generated code just as you would on code written by hand. Automation should raise a useful signal, not bury developers in noisy warnings.
- Check security advice against current sources. For authentication, cryptography, cloud permissions, and other sensitive areas, use official standards and vendor documentation as the reference. Ask the assistant for citations if that helps, but open the documents and verify the relevant section yourself. A citation that looks real can also be wrong or irrelevant.
- Review behavior, not just syntax. Ask what the code can read, change, or send. Does it validate the right input? Does it grant only the access the service needs? Does it protect secrets? Does the recovery flow weaken the main authentication method? A clean compile answers none of those questions.
- Ground the assistant in trusted information where possible. Retrieval-augmented generation, or RAG, supplies relevant material from a controlled source, such as approved product documentation. This can reduce unsupported answers, but it does not guarantee correctness. The retrieved content may be outdated, incomplete, or poorly matched to the question, so human review still matters.
- Track what happens in your own environment. Record how often suggestions include unknown packages, fail tests, or need security fixes. Review those results by tool, task, and language. The NIST Generative AI Profile offers risk-management guidance that teams can use when deciding what to measure and how to respond. A small set of useful measures is better than a dashboard full of numbers nobody acts on.
- Keep the final decision with a responsible person. A tool can draft code, but a human reviewer should own the decision to merge security-sensitive changes. Make the review practical: show the dependency change, the security assumptions, the tests run, and the trusted sources used. That gives reviewers something concrete to assess.
I have seen teams get better results when review questions are short and specific. “Is this safe?” invites a shrug. “Is this exact package published by the expected maintainer, and does this code need every permission it requests?” gives a reviewer a real task. Here’s the kicker: good guardrails do not need to be clever. They need to run every time.

Comparison: AI Suggestions vs. Manual Dependency Research
AI-assisted development is not the same as a traditional research process. Each has strengths, but they fail in different ways. The sensible choice is not to treat either method as automatically safe. Use AI to draft and explain, then apply checks that fit the risk of the change.
| Area | AI-generated suggestion | Manual research and established review |
|---|
| Speed | Produces an answer quickly and can draft example code. | Takes longer, especially when a developer is new to the tool or library. |
| Package discovery | May suggest a plausible name that is misspelled, outdated, or invented. | Lets a developer search registries and official documentation directly, though human mistakes remain possible. |
| Security context | May miss recent guidance or details about the project’s threat model. | Can use current standards and project-specific requirements, if the reviewer checks them. |
| Repeatability | Similar prompts can produce recurring suggestions, including recurring errors. | Results depend on the researcher and the quality of the review process. |
| Best use | Drafting routine code, tests, and explanations with verification. | Confirming package identity, security decisions, and production changes. |
Manual research is not a silver bullet. A rushed engineer can choose a risky dependency or copy a weak pattern from an old blog post. The useful difference is traceability: a careful review can point to the registry entry, current documentation, and reason for the decision. An assistant’s fluent explanation is not that evidence.
Likewise, AI output is not automatically dangerous. A suggestion can be accurate and save time when the developer checks it against the project’s needs. The important question is whether the team knows what evidence supports the choice. If a dependency affects a production build, reviewers should be able to identify its origin, purpose, version, and owner.
For many teams, the strongest process combines both approaches. Let an assistant help draft a test or explain an unfamiliar error, then have a developer verify important details using trusted sources and automated checks. Keep dependency changes visible in code review. That approach preserves speed without asking polished text to act as proof.
Common Mistakes to Avoid
The first mistake is treating confidence as evidence. A model may state an incorrect claim in a calm, clear tone. That is a feature of generated language, not a measure of truth. I have watched a tidy explanation make a questionable answer feel settled; the fix was to check the underlying package or specification, not argue about how convincing the prose sounded.
The second mistake is checking whether code compiles and stopping there. A compiler can catch missing functions and syntax errors. It will not tell you that an authentication method is weak for your risk level, or that a cloud policy grants far more access than the service needs. Add security-focused review and testing that match the change.
The third mistake is assuming that an existing package is safe. A registry entry may be new, abandoned, unrelated, or controlled by an unexpected publisher. Check who maintains it, what it does, how long it has existed, and whether the project actually needs it. An allowlist helps, but it also needs a process for reviewing new entries rather than turning into a permanent rubber stamp.
The fourth mistake is trusting a citation without opening it. Models can return broken links, point to the wrong section, or describe a document inaccurately. For security choices, read the source itself and make sure it applies to your environment. If a recommendation depends on a particular standard or platform, verify the version and scope.
The fifth mistake is placing every safeguard on individual reviewers. People get tired, deadlines get tight, and generated code arrives quickly. Expecting human attention to catch every unknown package is a weak control. Put checks in continuous integration, dependency review, and repository policy, then reserve people’s attention for decisions that need judgment.
Some teams make the opposite mistake and ban all AI tools without considering the actual risks. A blanket rule may be right for a particular system, but it is not a substitute for knowing which data can be shared, what code can be accepted, and how outputs are reviewed. Set boundaries based on risk. For example, do not paste secrets or private customer data into tools that are not approved for that use.
Finally, do not assume that retrieval or a benchmark fixes the problem on its own. RAG can provide better grounding, and benchmarks can reveal patterns, but neither proves that a specific answer is safe. Track results, update controls when the tools change, and keep accountable people involved. Let’s be real: a control that nobody checks can quietly become a box-ticking exercise.
Frequently Asked Questions
Can AI-generated code be trusted?
It can be used, but it should not be trusted automatically. Treat the output as a draft. Check dependencies against official registries, run tests and security scanners, and review sensitive code against current standards. The level of review should match the risk: a small formatting helper needs less scrutiny than code that handles passwords or grants cloud access.
What is slopsquatting?
Slopsquatting is a supply-chain attack based on package names hallucinated by AI tools. An attacker may register one of those names, then wait for a developer to install it after receiving the suggestion. The practical defense is to verify the exact package and publisher before installation, and to use reviewed dependency controls in automated builds.
How can a team check whether a suggested package is real and safe?
Search the official registry for the exact name, then review the maintainer, release history, source code, documentation, and project purpose. Confirm that the suggested API matches the installed version. Check for vulnerabilities and review transitive dependencies. A package being present in a registry does not, on its own, make it trustworthy.
Should AI assistants write authentication code?
They can help draft examples or tests, but security-sensitive authentication needs review by someone familiar with current standards and the system’s risks. Check the complete flow, including account recovery, session handling, rate limits, and the way credentials are stored. Use current guidance for phishing-resistant authentication where appropriate, rather than accepting a familiar snippet without question.
Final Thought
AI coding tools can help people get useful work done. They can also make it easier for a wrong answer to move quickly from a chat window into a dependency file or production service. The answer is neither panic nor blind trust. It is to treat generated suggestions like any other unverified input, then build checks that catch the mistakes people will eventually miss.
When I think about the best engineering teams, I notice a simple habit: they respect the work enough to verify it. That means asking where a package came from, what a permission allows, and whether an authentication pattern still meets the need. It also means respecting users, whose data and access depend on decisions made far from their view. The dignity of good work includes care for the people who rely on it.
Use AI where it helps. Keep dependency checks, tests, and security review close to the code. Measure what your tools get wrong, and update the rules when the evidence changes. Those steps let teams benefit from faster drafting without handing authority to a confident answer. The goal is not perfect software; no serious engineer should promise that. The goal is a responsible process that catches likely failures before they reach the people a system is meant to serve.
—Ermenildo Castro