AI coding assistants write a large share of the code teams ship. Veracode's 2026 GenAI Code Security Report estimates that AI authors roughly half of all committed code at teams that have adopted these tools. That speed is valuable, but the assistants are built to produce working code, not secure code, and none of them know your internal security standards. This guide lays out a practical workflow for securing AI-generated code: how to prompt for it, scan it, vet its dependencies, review the riskiest changes, set policy, and automate enforcement so security keeps pace with machine-speed development.
What Are the Security Risks of AI-Generated Code?
AI-generated code tends to fail in four recognizable ways:
- Hallucinated packages. Models sometimes reference libraries that do not exist. Attackers can register those names and fill them with malicious code.
- Hardcoded secrets. Example code often carries example credentials, and real keys end up committed alongside it.
- Insecure coding patterns. Injection flaws such as cross-site scripting and log injection appear because the model cannot see how untrusted data flows through the wider application.
- Design and logic flaws. Broken authorization, data exposed in query strings, and missing rate limits can compile cleanly and still pass a basic scan.
The research is consistent. Veracode's 2026 GenAI Code Security Report tested more than 100 models across four snapshots. Syntax pass rates reached 99.9%, yet the average security pass rate stayed around 56%. In roughly 44% of tasks, models introduced a detectable OWASP Top 10 vulnerability. Results varied widely by flaw type: models handled SQL injection well (83% pass rate) but performed poorly on cross-site scripting (15%) and log injection (12%).
Secrets show the same pattern. GitGuardian's State of Secrets Sprawl 2026 report, as covered by SC Media, found that public commits co-authored by Claude Code leaked secrets at 3.2%, about twice the 1.5% baseline across all public GitHub commits. It also found more than 24,000 secrets exposed in public MCP configuration files.
On dependencies, a USENIX Security 2025 study of 16 code-generating LLMs and 576,000 code samples found average package hallucination rates of at least 5.2% for commercial models and 21.7% for open-source models, with 205,474 unique hallucinated package names.
The good news is that these risks follow predictable patterns. You can manage predictable risks with a repeatable workflow, which is what the rest of this guide covers.
Guide the AI With Security-Focused Prompts
Vague prompts tend to produce code with security gaps. Veracode's testing deliberately gave models no security-specific guidance because developers usually focus on functionality and don't always know when a request has security implications. Under those conditions, models chose an insecure implementation in nearly half of tasks. Stating security requirements up front closes part of that gap.
A stronger prompt names the controls you expect, not just the feature:
- Weak: "Build an API endpoint that deletes a user."
- Stronger: "Build an API endpoint that deletes a user. Require bearer-token authentication in the Authorization header, not the query string. Pass the user ID in the request body and verify the caller is authorized to delete that specific user. Validate all inputs, use parameterized queries, rate-limit the endpoint, and do not hardcode any credentials."
The stronger version targets the exact flaws Salt Code flags in its own demo: broken object-level authorization (OWASP API1), auth tokens in the query string (API2), and user IDs leaking through URLs (API3).
Keep a shared library of vetted secure-coding prompts so the whole team starts from the same baseline. Even so, prompt discipline depends on every developer remembering every requirement on every request. That's why the later steps, and automated enforcement, matter.
Scan Every Change With Automated Security Tools
Run three kinds of automated checks on every AI-suggested change, not just before a release:
- Static application security testing (SAST) to catch insecure code patterns such as injection flaws.
- Software composition analysis (SCA) to flag vulnerable or suspicious third-party packages.
- Secrets detection to stop credentials before they are committed. GitGuardian's own recommendation is to scan code changes for secrets before committing them.
Place these checks in two spots. In the IDE, they give developers instant feedback while the code is still fresh. In CI, they act as a gate that blocks a merge when a check fails.
Scanning has a limit worth naming. As Salt Code puts it, SAST and DAST tools catch problems downstream, after code is committed, reviewed, and queued for deployment, so every fix becomes a rewrite. Veracode's data also shows why scanners alone fall short on some flaw classes: catching cross-site scripting and log injection requires tracking how user input flows across files and functions, which a model generating a single function cannot see. Tune your scanners for the patterns AI tools produce, and pair them with prevention earlier in the workflow.
Verify Every Dependency Before It Enters Your Codebase
AI coding tools sometimes suggest packages that do not exist. The USENIX Security 2025 study describes this as a new form of package confusion attack: an attacker registers the hallucinated name on a public registry such as PyPI or npm, publishes malicious code under it, and waits for a developer to run the install command the AI suggested. The researchers found the problem was persistent and systemic across models.
Before installing any package an AI tool suggests, confirm three things:
- It is real. Check that the package exists on the official registry under the exact name, and watch for near-miss spellings of popular libraries.
- It is actively maintained. Look at release history, maintainer activity, and download volume. A brand-new package with no history deserves scrutiny.
- It is free of known vulnerabilities. Run it through your software composition analysis tool before it reaches a lockfile.
Then keep a software bill of materials (SBOM). An SBOM is a list of the open-source and third-party components in your code, with their versions, licenses, and patch status, as the CMS Information Security and Privacy Program explains. Generating it in CI gives you a running record of every component an AI tool has introduced, so you can respond quickly when a new vulnerability is disclosed.
Reserve Human Review for High-Risk Changes
Automated tools cannot catch every business logic flaw, and reviewers cannot read every AI-generated line at machine speed. Focus human review where a mistake costs the most:
- Authentication and authorization. Access control deserves the closest look. Gartner's How to Secure Custom-Built AI Agents report finds that access control issues will cause most agentic security failures.
- Cryptography. Algorithm choice, key handling, and random number generation.
- Sensitive data handling. Anything that touches PII, payment data, or health data, including where that data is logged.
- New external endpoints, agent tools, and MCP servers. Each new API or MCP integration expands your attack surface. Gartner also notes that most published MCP servers lack content sanitization, making public MCP servers a significant and underestimated attack vector.
Separate the person who prompted a risky change from the person who approves it. A developer who iterated with an AI assistant until the code worked is the least likely to spot what the assistant got wrong.
Review also does not end at merge. As Salt's Nick Rago explains in Your AI Transformation Needs Runtime Protection for the Whole Agentic Estate, a single prompt can travel from an agent through an LLM and MCP servers to the APIs that run your business. An attacker who learns about an exposed tool can skip the agent entirely and call the API behind it. The code your AI assistants write becomes part of that path, so validate it at runtime as well as in review.
Set a Lightweight Governance Policy for AI Coding Tools
Write a short, practical policy rather than a lengthy compliance document. A policy people can read in five minutes is a policy people follow. Salt Code names the alternative plainly: when policies live in PDFs, wikis, and tribal knowledge, the AI building your software has read none of them.
At minimum, the policy should state:
- Where AI tools are allowed. Which assistants are approved, for which repositories, and whether any code (such as cryptographic or payment modules) is off-limits.
- What must be scanned. The SAST, SCA, and secrets checks every AI-assisted change must pass, and where they run.
- What needs human review. The high-risk categories from the previous section.
- Who owns exceptions. A named owner who can approve a deviation and record why.
Tag AI-generated commits so teams can trace an issue back to how the code was created. Commit metadata is what made GitGuardian's Claude Code findings possible in the first place: the researchers could compare leak rates only because those commits carried a co-author tag. The same tagging lets your team measure whether its AI-assisted code is getting safer over time.
Automate Enforcement With an AI Code Governance Platform
Every step above works only if developers remember to do it, on every prompt, under deadline pressure. A dedicated governance platform applies these steps automatically. When evaluating one, look for:
- Prevention at the point of generation. Policies should shape the code while the AI writes it, not only flag problems after commit.
- Coverage across your assistants. Developers use several tools; one policy model should govern them all.
- Pipeline and runtime enforcement. Checks in CI/CD that block violations before production, plus monitoring of how APIs, MCP servers, and agents actually behave once deployed.
- Prioritization based on real exposure. Findings ranked by what is reachable and exploitable, so teams fix what matters first.
- Clear audit trails. Records of which policies applied to which code, for compliance and incident response.
Salt Code is built for this workflow. Its goal is to make AI-generated code compliant as soon as it is created, not after the fact. Salt Code connects the Salt Posture Governance Engine to the tools developers already use and carries enforcement from prompt to production:
- Discover every API, MCP server, and AI agent integration across code repositories and cloud environments.
- Enforce during code generation by translating security policies into rules that guide AI coding assistants in real time.
- Govern in the pipeline by validating policy in CI/CD and pull requests and blocking violations before production.
- Validate at runtime by monitoring APIs, MCP integrations, and agents for policy violations, posture gaps, and anomalous activity.
- Remediate and improve by feeding runtime findings back into developer workflows and the AI assistants themselves.
Salt Code ships with 140+ pre-built policies, covering frameworks from the OWASP API Security Top 10 to the MCP Security Top 10, plus your own custom rules. It works with Claude Code, Cursor, GitHub Copilot, Windsurf, Kiro, Codex, Gemini CLI, JetBrains, and any AI coding assistant that supports MCP server configuration.
Teams that want to start immediately can use the free version of Salt Code. It installs in about 60 seconds, adds 40 security policies across API security, MCP security, LLM security, and OpenAPI compliance, and is active from the next prompt. According to Salt, it 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.
To see it in action, watch the on-demand webinar Secure AI Written Code Before It Ships: Salt Code, which includes a live walkthrough of Salt Code enforcing policies across AI coding assistants in real time.
Frequently Asked Questions
How do you prompt AI to write more secure code?
State security requirements in the prompt rather than asking only for the feature. Ask explicitly for input validation, parameterized queries, authentication and authorization checks, safe handling of tokens and IDs, and no hardcoded secrets. Keep a shared library of vetted prompts so the whole team starts from the same baseline, and use a tool that injects security policies automatically so protection does not depend on memory.
Do you still need human review of AI-generated code?
Yes, but targeted. Veracode found that even the best-performing model in its 2026 testing still failed about one in three security tasks. Focus human review on authentication and authorization, cryptography, sensitive data handling, and new endpoints, agent tools, or MCP servers, and let automation handle the rest.
Which tools help secure AI-generated code?
A layered set: static analysis (SAST) for insecure patterns, software composition analysis (SCA) for vulnerable or nonexistent packages, secrets detection before commit, SBOM generation for component tracking, and an AI code governance platform such as Salt Code that enforces policy inside the coding assistant itself.
How do you keep secrets out of AI-generated code?
Never paste real credentials into prompts or example code. Reference secrets from a vault or secrets manager, run secrets detection in the IDE and as a pre-commit and CI check, and audit MCP configuration files, which GitGuardian found to be a growing source of leaked credentials. If a secret does leak, rotate it immediately rather than only deleting it from the latest commit.
Should AI-generated code go through a separate review process from human-written code?
It should meet the same security bar, with extra checks matched to how AI fails: package verification, secrets scanning, and closer review of high-risk categories. Tagging AI-assisted commits makes this practical, because it lets you route those changes to the right checks and measure results over time.
.jpg)