Salt expands Agentic Detection and Response with LLM runtime and prompt security

Industry

AI Code Security Best Practices

November 24, 2026

Danielle Duhon
Director of Growth

Every company has a security standard for how code should be written. Your AI coding assistant has never read it. That gap matters more every month, because AI now writes a large share of enterprise code, and that code increasingly becomes the APIs, MCP servers, and agent tools your business runs on. This guide explains what AI code security is, where AI-generated code tends to go wrong, why coding assistants miss the context that makes code safe for your environment, and the best practices security teams can use to govern AI-generated code without slowing developers down.

What Is AI Code Security?

AI code security is the practice of identifying and mitigating the vulnerabilities that AI coding assistants and generative models introduce across the software development lifecycle. It covers code written in tools like Claude Code, Cursor, GitHub Copilot, and Windsurf, from the first prompt through production.

It differs from traditional code security in one important way. A human developer writing code at your company usually knows there is a "company way" to do things. They can read the internal standard, ask AppSec, or copy patterns from existing services. An AI model knows none of that. It generates code from patterns it learned elsewhere, without knowing your threat model, authorization patterns, or compliance requirements. As Salt CEO Roey Eliyahu put it, unless you bring the policy to the assistant, the assistant will improvise.

This guide focuses on two related disciplines:

  1. Securing the code AI produces, ideally at the moment it is generated.
  2. Reviewing that code before it reaches production, with the right mix of automation and human judgment.

For a step-by-step workflow you can put into practice today, see our companion guide, How to Secure AI-Generated Code.

Why AI-Generated Code Introduces New Security Risk

AI coding is now the default. In the 2025 Stack Overflow Developer Survey, 84% of respondents said they use or plan to use AI tools in their development process, and 51% of professional developers use them daily. Inside the enterprise, the picture is the same. In Salt Security's research report, AI Coding Assistants and the New Security Challenge, 67% of security leaders said AI coding assistants are widely adopted across their development teams, and 90% said they have active concerns about AI-generated code.

Code volume has outrun review capacity. Security review was built for a world where humans wrote code at human speed. That world is gone. The same Salt research found that 38% of organizations still rely primarily on manual review for AI-generated code, and it warns that reviewer fatigue and inconsistent enforcement are creating "security drift" across development environments. When code volume grows faster than the number of qualified reviewers, something gets merged without a second look.

Developers grow overconfident in AI output. Developers say they are skeptical of AI. In the Stack Overflow survey, more developers distrust AI tools' accuracy (46%) than they trust them (33%). But stated skepticism does not always change behavior. A Stanford user study published at ACM CCS 2023 found that participants with access to an AI assistant wrote significantly less secure code than those without one, and were also more likely to believe their code was secure. Participants who produced secure solutions trusted the AI less and edited its output more.

That combination is the core problem. More code, less time to review it, and a tool that makes insecure code look finished.

Common Security Risks in AI-Generated Code

AI-generated code fails in patterns. Knowing the patterns is the first step to governing them.

Hallucinated Dependencies and Software Supply Chain Exposure

Large language models sometimes invent package names that do not exist in public registries. A USENIX Security 2025 study of 16 code-generating models and 576,000 code samples found average hallucination rates of at least 5.2% for commercial models and 21.7% for open-source models, with 205,474 unique made-up package names.

Each fake name is an opportunity for an attacker. They register the hallucinated name on PyPI or npm, publish a malicious payload under it, and wait for a developer to run the install command the AI suggested. The researchers describe this as a new form of package confusion attack; the industry has also started calling it slopsquatting.

The defense is simple to state and easy to skip: verify every AI-suggested dependency before it enters the codebase. Confirm the package exists under the exact name, check its maintenance history, and run it through your software composition analysis tool against a vulnerability database.

Hardcoded Secrets and Credential Leaks in Generated Code

AI models learn from public code, and public code is full of secrets. GitGuardian's State of Secrets Sprawl 2026 report found 28.65 million new hardcoded secrets in public GitHub commits in 2025, as reported by SC Media. The same report found that commits co-authored by Claude Code leaked secrets at 3.2%, roughly double the 1.5% baseline across all public commits.

Those secrets end up in public repositories, in application logs, and increasingly in AI tooling itself: GitGuardian found more than 24,000 secrets exposed in public MCP configuration files. Secrets scanning in the IDE and as a pre-merge check is the most direct way to catch hardcoded API keys, tokens, and credentials before they ship.

Injection Flaws and Other Insecure Coding Patterns

AI assistants often take the shortest path to working code. For database queries and system commands, that shortest path is frequently string concatenation, which opens the door to SQL and command injection. In the Stanford user study, the AI assistant often wrote correct SQL queries by concatenating strings instead of using prepared statements.

The research on real-world code is consistent. An empirical study of AI-generated code in GitHub projects, published in ACM Transactions on Software Engineering and Methodology, analyzed 733 snippets from Copilot, CodeWhisperer, and Codeium. It found security weaknesses in 29.5% of Python and 24.2% of JavaScript snippets, spanning 43 CWE categories, eight of them on the 2023 CWE Top 25. Veracode's 2026 GenAI Code Security Report found that across more than 100 models, AI-generated code introduced a detectable OWASP Top 10 vulnerability in roughly 44% of tasks.

Other recurring patterns include:

  • Missing input validation, especially where user input is later rendered or logged. Veracode measured pass rates of just 15% for cross-site scripting and 12% for log injection.
  • Weak cryptography and randomness. CWE-330, use of insufficiently random values, was among the most common weaknesses in the GitHub study. In the Stanford study, AI-assisted participants were more likely to use trivial ciphers.
  • Insecure defaults include tokens passed in query strings, missing rate limits, or overly permissive data access.

Prompt Injection and Other Attack Vectors Unique to AI Coding Tools

Prompt injection is an attack in which adversarial instructions are hidden in content the AI reads, such as code comments, variable names, documentation, or configuration files, to manipulate its output. Coding assistants are especially exposed because they read so much of the repository to build context.

The "Rules File Backdoor" technique, disclosed by Pillar Security in 2025 and covered by SC Media, shows how this works. Researchers hid instructions inside a rules file using invisible Unicode characters. The file appeared to say "follow HTML5 best practices," but also told the assistant to add an external script to every file and not mention it. Both GitHub Copilot and Cursor followed the hidden instructions without telling the user.

The root issue is that a model treats developer context and attacker instructions as the same input: text. It cannot reliably tell them apart. Defenses include:

  • Input filtering. Scan rules files, prompts, and shared AI configuration for hidden Unicode and unusual formatting, and treat AI configuration files with the same scrutiny as executable code.
  • Mandatory human review for any AI-generated change that touches authentication, authorization, or access control.
  • Watching for unexpected additions in generated code, such as new external resource references or network calls.

Why AI Coding Tools Miss Business and Architectural Context

An AI coding assistant sees the prompt and whatever files it pulls into context. It does not see your organization. It does not know that your APIs require a specific authorization pattern, that certain data classes can never be returned to an agent, that tokens are forbidden in tool configuration, or that every public endpoint needs an OpenAPI schema. As Roey Eliyahu wrote in this blog post about Salt Code, assistants know common patterns from the internet. Some are good. Some are outdated. Some are completely wrong for your environment.

That gap produces a specific kind of failure: code that runs correctly but is architecturally wrong for where it lands. Picture a developer asking an assistant to build a support tool that looks up orders and issues refunds. The assistant generates an MCP server that calls internal APIs touching customer records and payment systems. Every function works. But if that MCP server has weak authorization, a hardcoded credential, or no rate limit, it becomes part of the action layer your agents use to touch the business. The flaw is not in any single line. It is in how the code fits the environment.

Context also decides which flaws to fix first. A missing input check in an internet-facing API that an agent can call is a very different risk from the same bug in an isolated internal script. Scanners that report findings without knowing what is exposed, reachable, or connected to sensitive data leave teams triaging a flat list. Effective AI code security connects what was written to how it is deployed and who can reach it.

Best Practices for Securing AI-Generated Code

Reviewing AI-Generated Code: Manual and Automated Approaches

Automated scanners are good at known patterns: a concatenated query, a weak hash function, a hardcoded key. They are much weaker at business logic flaws and architectural mistakes, like an endpoint that checks whether a user is logged in but not whether they own the record they are deleting. Catching those takes human judgment about how the code should behave in your environment.

Treat AI-generated code with at least the same review rigor you apply to human-written code. Give extra attention to authentication, authorization, and data handling, where a subtle mistake has the largest blast radius. Stanford research offers a useful signal: participants who produced secure code questioned and edited the AI's output rather than accepting it as finished.

No single technique is enough. A layered testing strategy uses each method for what it does best:

  • Static analysis (SAST) catches insecure code patterns early, before code runs.
  • Dynamic testing (DAST) finds issues that only appear when the application is running and receiving real requests.
  • Manual review covers business logic, architecture, and the high-risk areas automation misses.

Building Security Policies and Governance for AI Coding Tools

Governance starts before the first prompt. Define which AI models, coding assistants, and MCP servers are approved for use, and make that list easy to find. Each approved MCP server is a new integration with access to your code and context, so it deserves the same vetting as any third-party dependency.

Restrictive or slow policies create their own risk: shadow AI, where developers turn to unsanctioned tools to get work done. Sonar's State of Code developer survey, summarized here, found that across the top ten AI coding tools, 35% of developers access them through personal accounts rather than work-sanctioned ones. The same survey found teams juggle four different AI tools on average. When code is written in tools security cannot see, policy cannot reach it. The goal is to make the approved path the easiest path.

Visibility matters as much as policy. Teams need to know which code in a repository was AI-generated so they can apply targeted review and trace a vulnerability back to its source. Tagging AI-assisted commits is a practical starting point; it is also what allowed GitGuardian to measure leak rates for AI-co-authored commits in the first place.

Embedding Security Checks Throughout the SDLC and CI/CD Pipeline

Run static analysis, software composition analysis, and secrets detection automatically on every commit and pull request that involves AI-suggested code. Automation keeps pace with AI-speed development in a way manual review cannot.

Back those checks with policy-driven gates. If AI-generated code introduces a critical vulnerability, a hardcoded secret, or an unapproved dependency, the pipeline should block the deployment rather than log a warning that someone may read later.

Finally, keep watching after deployment. Some issues only surface once code is running: an API that behaves differently under real traffic, an MCP integration that exposes more data than intended, or an agent that calls a tool in a way no one anticipated. Continuous monitoring in runtime closes the loop. As Salt puts it, code tells you what was built, configuration tells you how it is governed, and runtime tells you what happened.

Choosing a Solution to Govern and Review AI-Generated Code

The practices above work. The problem is keeping them consistent across every developer, every assistant, and every commit. When evaluating a platform for AI code review and governance, security teams should weigh:

  • Visibility into AI usage. Can it show which assistants are in use, which policies are being applied, and which APIs, MCP servers, and agent integrations exist across your repositories and cloud environments?
  • Policy enforcement at the point of generation. Does it shape code while the AI writes it, or only flag problems after commit?
  • Coverage across assistants. Developers use several tools. One policy model should govern Claude Code, Cursor, Copilot, and whatever they adopt next.
  • Your standards, not just generic ones. Can you bring your own internal policies alongside frameworks like the OWASP API Security Top 10?
  • Pipeline and runtime validation. Does enforcement continue into CI/CD and production, where code becomes real behavior?
  • A feedback loop. Do runtime findings flow back to developers and assistants so the next generation of code is better than the last?

A dedicated governance layer catches what individual developers and point scanners miss in AI-heavy workflows, because it carries the same standard everywhere code is created, merged, and run.

That is the idea behind Salt Code. Rather than reviewing AI-generated code after it is written, Salt Code enforces your security policies inside the AI coding assistants your developers already use. It connects Salt's Posture Governance Engine to tools like Claude Code, Cursor, GitHub Copilot, Windsurf, Kiro, Codex, and Gemini CLI, and to any assistant that supports MCP server configuration. Policies are applied as code is generated, validated again in CI/CD and pull requests, and checked against how APIs, MCP integrations, and agents actually behave at runtime. Salt Code ships with 140+ pre-built policies, spanning the OWASP API Security Top 10, the MCP Security Top 10, and your own custom rules.

For developers, it works in the background. For security teams, the standard finally leaves the wiki and becomes part of how code is created. Seasoned engineers, citizen developers, and overnight prototypes all answer to the same policies.

Teams that want to start today can try the free version of Salt Code. It installs in about 60 seconds and gives your coding agent 40 security policies across API security, MCP security, LLM security, and OpenAPI compliance, active from your very next prompt. Salt Code injects security context into the agent's context window, so your code never leaves your machine. The enterprise plan adds custom policy packs, org-wide management, prompt-time security reporting, and SSO/SCIM.

For a step-by-step workflow to pair with these practices, read our companion guide, How to Secure AI-Generated Code.

Frequently Asked Questions

Is AI-generated code secure by default?

No. AI models can produce code that compiles and runs, but security is a separate skill. Veracode's 2026 testing of more than 100 models found a 99.9% syntax pass rate but an average security pass rate of about 56%. Without security guidance, models introduced a known vulnerability in roughly 44% of tasks.

How does the vulnerability rate in AI-generated code compare to human-written code?

Early evidence points to higher rates for AI-generated code. CodeRabbit's analysis of 470 open-source pull requests, reported by DevOps.com, found that AI-co-authored pull requests had about 1.7 times more issues overall and 1.5 to 2 times more security vulnerabilities than human-only ones. GitGuardian likewise found AI-co-authored commits leaked secrets at about twice the baseline rate. Sample sizes and methods vary, so treat the exact multipliers as directional.

Does banning AI coding tools reduce an organization's security risk?

Rarely. With 84% of developers using or planning to use AI tools, a ban tends to push usage out of sight rather than stop it. Sonar's developer survey found 35% of developers already access top AI coding tools through personal accounts. Code written in tools security cannot see is code security cannot govern. Approving tools, enforcing policy inside them, and monitoring the results is a more reliable way to reduce risk.

What questions should security teams ask AI coding tool vendors?

Start with: Does our code or prompt data leave our environment, and is it retained or used for training? Can we enforce our own security policies inside the tool? What admin controls, audit logs, and SSO options exist? How does the tool handle MCP servers, extensions, and rules files, and can we restrict which ones developers connect? And how does it help us see which code it generated?

Do developers write less secure code when they rely on AI coding assistants?

Research suggests they can. In a Stanford user study published at ACM CCS 2023, participants with access to an AI assistant wrote significantly less secure code than those without one, and were more likely to believe their code was secure. Participants who trusted the AI less and edited its output more produced more secure code. The lesson is not to avoid AI, but to pair it with guardrails that do not depend on developer vigilance alone.

How can businesses safely adopt AI coding tools throughout their development workflow?

Approve the assistants and MCP servers developers can use, and make the approved path the easy one. Bring your security policies into the assistant so code is generated to standard from the first prompt. Run SAST, software composition analysis, and secrets detection on every AI-assisted change, with gates that block critical issues. Reserve human review for authentication, data handling, and new endpoints. Then monitor runtime behavior and feed what you learn back to developers. A platform like Salt Code is designed to carry that policy from prompt to production.

Our latest posts