Vibe Coding Security: The Complete Guide to Securing AI-Generated Code
What vibe coding security means, the 4 core risks—prompt injection, agent permissions, unsafe tools, and MCP—and how to scan AI-generated code before it ships.
Vibe coding security is the practice of scanning, testing, and governing code that AI tools such as Cursor, Claude Code, and Windsurf generate before it ships. It covers the code itself, the permissions granted to the coding agent, the tools the agent can call, and the MCP integrations that connect it to files, APIs, credentials, and other systems.
Why vibe coding security differs from traditional AppSec
Traditional application security usually reviews code after a developer has formed a mental model of the change. In a large AI-generated diff, the developer may be reviewing primarily for whether the feature works. That makes it easier to miss a broken authorization check, an unnecessary package, a secret copied into client code, or a tool call with a much larger blast radius than the task required.
The problem is not that every AI-generated line is insecure. A 2025 study of 7,703 files found that most analyzed files had no identifiable CWE-mapped vulnerability, while still finding 4,241 CWE instances across 77 vulnerability types. The practical lesson is to verify generated code with language-aware, context-aware security checks instead of assuming that functional output is safe output.
Coding agents also introduce a runtime security problem. They can read untrusted repository content, run shell commands, install dependencies, call external tools, and sometimes reach deployment or production systems. Security therefore has to evaluate both what the agent writes and what it is allowed to do.
The four core risk categories
1. Prompt injection in AI coding workflows
Prompt injection happens when a coding assistant ingests untrusted content—a repository file, webpage, issue, retrieved document, or MCP tool result—and treats instructions inside that content as authority. A malicious instruction can try to steer the agent toward reading secrets, weakening authentication, installing a package, or calling a tool the developer never intended to use.
The defense is not a phrase blacklist. Separate trusted instructions from untrusted content, validate tool inputs, restrict downstream actions, and review the entire source-to-action path. How to detect prompt injection in AI-generated code provides a deeper method and concrete tests.
2. Agent permission escalation and excessive agency
Coding agents often receive terminal, filesystem, package-manager, source-control, cloud, or database access so they can complete work autonomously. Without a permission boundary, a narrow editing task can expand into a shell command, schema change, force-push, or production action without a human decision at the moment of risk.
Use a distinct agent identity, grant the minimum tools and scopes required for the task, and require approval before high-impact or irreversible actions. AI agent security checklist for developers provides a complete control set for identity, permissions, execution, memory, monitoring, and incident response.
3. Unsafe tool use by autonomous agents
Agentic coding tools do more than generate text: they invoke package managers, deployment scripts, API clients, database tools, and shell commands. A tool call can be syntactically valid and still be unsafe because it targets the wrong environment, affects too many records, exposes sensitive data, or cannot be rolled back.
Treat every tool as an explicit capability. Give it a strict input schema, validate the target and environment outside the model, apply rate or volume limits, and use allow, block, or approval decisions based on impact. Log the requested action, agent identity, decision, approval state, and final outcome.
4. MCP and retrieval security gaps
MCP servers and retrieval pipelines extend what an AI agent can see and do, which also expands its attack surface. Risks include malicious server launch commands, over-broad scopes, token misuse, unsafe authorization flows, server-side request forgery during metadata discovery, tool poisoning, and indirect prompt injection in retrieved content.
Review an MCP server like executable third-party integration code: verify its publisher and launch command, pin the version, inspect the credentials and scopes it receives, restrict filesystem and network access, and require approval for sensitive tools. MCP security risks for Claude Code users provides the complete pre-install review.
Six failure patterns to check in AI-generated code
1. Missing authentication and authorization
Generated endpoints often implement the happy path and omit the negative path. An API may check that a user is signed in but never verify that the requested record belongs to that user. Admin, billing, key-management, and internal routes may be callable without an explicit role or scope decision.
- Require authentication on every non-public route.
- Check authorization against the exact object and action, not only the user’s login state.
- Test cross-user, cross-project, and cross-tenant access.
- Keep privileged checks on the server; hiding a button in the client is not authorization.
- Use deny-by-default rules for admin, billing, secrets, grants, and destructive operations.
2. Injection and unsafe output handling
AI-generated code can compose untrusted input into SQL, HTML, shell commands, paths, URLs, templates, or dynamic code. The same problem appears one level higher when model output reaches eval, exec, subprocesses, file operations, or MCP tools.
- Use parameterized queries and safe framework APIs instead of string construction.
- Encode output for its destination and avoid unsafe HTML rendering.
- Validate command arguments, file paths, URLs, and redirect destinations with narrow allowlists.
- Do not execute raw model output.
- Trace untrusted input across helper functions instead of reviewing only the final line.
How to detect prompt injection in AI-generated code covers the model-specific version of this source-to-sink review.
3. Secret exposure and unsafe data handling
Generated examples frequently use convenient placeholders that become real credentials, copy server secrets into client code, log full request objects, or send sensitive context to a model. Once a secret is committed, bundled, or logged, deleting the line is not enough; the credential must be rotated.
- Keep secrets in server-side environment or secret-management systems.
- Never expose private keys through public environment-variable prefixes or browser bundles.
- Redact credentials, tokens, cookies, personal data, and sensitive tool arguments from logs.
- Give AI tools only the minimum context needed for the task.
- Scan commits and generated files for secrets before they leave the workstation.
A real example: how a hardcoded secret gets shipped
A developer asks an AI assistant to add Stripe to a prototype. The assistant optimizes for a working demo and places a test secret in a client-side module. The page loads, the checkout works, and the change is committed. Nobody explicitly requested a hardcoded key, but nobody defined the secret boundary either.
// client/stripe.ts
export const stripeSecret = 'sk_test_example_placeholder'Even a test credential should not be shipped in a browser bundle or committed to source. If a real credential reaches either location, remove it and rotate it; deleting the line does not invalidate an exposed key.
// server/stripe.ts
const stripeSecret = process.env.STRIPE_SECRET_KEY
if (!stripeSecret) {
throw new Error('STRIPE_SECRET_KEY is required')
}The safer version keeps the secret in a server-only environment, fails clearly when configuration is missing, and never sends the secret to the client. A security scan should still confirm that the file is not imported into a client bundle and that logs and errors do not expose the value.
4. Hallucinated and unverified dependencies
A model can suggest a package that does not exist, choose the wrong package with a similar name, or select an old and vulnerable version. Attackers can publish packages that match plausible hallucinated names—a supply-chain pattern often called slopsquatting.
- Verify every new package in the authoritative registry and the project’s official documentation.
- Check publisher, repository, maintenance history, release age, and install scripts.
- Pin reviewed versions and commit the lockfile.
- Remove generated dependencies that duplicate platform or existing-project functionality.
- Run dependency and license checks before merge.
5. Weak defaults and incomplete production controls
Generated applications often work locally with permissive settings that are unsafe in production: wildcard CORS, disabled certificate checks, broad file permissions, missing CSRF protection, verbose errors, weak cookie settings, no rate limits, and unrestricted request bodies.
- Review every security-relevant default separately for development and production.
- Use secure, HTTP-only, same-site cookies where session cookies are appropriate.
- Set request-size, upload, timeout, retry, and rate limits.
- Return calm public errors and keep stack traces and internal details out of responses.
- Fail startup when required production secrets or security settings are missing.
6. Destructive agent actions
When a coding agent can run commands, edit files, change schemas, publish packages, or deploy, a code-review mistake becomes an action-control problem. A correct tool call can still be unsafe because the agent chose the wrong target or acted on hostile context.
- Use a disposable branch or workspace for generated changes.
- Sandbox commands and generated code with limited file and network access.
- Require approval for schema changes, authentication changes, releases, destructive commands, and production writes.
- Set iteration and cost limits outside the model.
- Keep a searchable record of requested, denied, approved, and completed actions.
AI agent security checklist for developers provides the full control set. If the action path runs through a connector, review MCP security risks for Claude Code users as well.
A repeatable vibe coding security workflow
Before generation
- Define the trust boundaries, sensitive data, protected actions, and acceptance criteria.
- Give the agent a narrow task and the minimum tools and context needed.
- State security requirements explicitly, including authentication, authorization, validation, errors, and tests.
During generation
- Keep changes small enough to understand and review.
- Ask for explanations of data flow and permission decisions, then verify them in code.
- Do not approve new packages, migrations, or broad configuration changes automatically.
- Run generated code in an isolated development environment.
Before merge or deployment
- Review the diff manually and remove unrelated generated changes.
- Run tests, static analysis, secret scanning, and dependency checks.
- Test unauthorized and malformed requests, not only the success path.
- Review infrastructure, environment, migration, and workflow files with the same care as application code.
- Require a human decision for high-impact release actions.
What secure vibe coding looks like
Secure vibe coding does not require rejecting AI-generated code or memorizing every generated character. It requires understanding what crosses each trust boundary, who can perform each sensitive action, which dependencies and credentials are involved, what will execute, and how unsafe behavior is blocked, approved, or recorded.
Frequently asked questions
What is vibe coding?
Vibe coding is a software-development workflow in which a developer describes an outcome to an AI coding assistant and iterates on the generated result instead of writing every line manually.
Is AI-generated code less secure than human-written code?
Not every AI-generated file is insecure, and security depends on the model, language, task, prompt, surrounding code, and review process. The important difference is that generated code can be accepted without the author-level understanding that normally helps reviewers notice trust-boundary and permission mistakes.
What is MCP security?
MCP security covers the risks created when AI applications connect to tools and data through Model Context Protocol servers. Important controls include scoped authorization, trusted installation, strict tool schemas, restricted filesystem and network access, token validation, approval for sensitive actions, and audit logs.
Can prompt injection affect code an AI writes?
Yes. If a coding agent reads untrusted files, webpages, issues, retrieved documents, or tool output, instructions embedded in that content can influence the code it writes or the tools it calls. Permissions and validation are still required because prompt filtering alone is not a complete security boundary.
How do I check AI-generated code before shipping it?
Review the diff, scan for secrets and common vulnerability patterns, verify every new dependency, test unauthorized and malformed requests, inspect new agent permissions and MCP connections, and require human approval for high-impact actions such as migrations, deployments, and destructive commands.
Does VibeLint replace code review?
No. VibeLint adds automated security checks and agent-control evidence to the workflow, but developers should still review important code and make the final decision on sensitive changes.
Sources and further reading
- NCSC: The 'vibe coding spectrum' approach to AI-assisted software development — Current government guidance on matching oversight to the level of AI autonomy.
- Security Vulnerabilities in AI-Generated Code: A Large-Scale Analysis of Public GitHub Repositories — The 7,703-file CodeQL study referenced in this guide.
- OWASP Top 10 for Agentic Applications — Agentic risk guidance covering goal hijacking, tool misuse, identity, privilege, and other control failures.
- Model Context Protocol security best practices — Official MCP guidance for authorization, token handling, SSRF, local server installation, scopes, and sessions.