Back to blog posts

15 min

An engineering team's guide to AI code security

AI code security guide: five attack vectors targeting coding agents and six controls to apply, from microVM isolation to approval gates.

Nicolas LecomteNico is a founder of Blaxel, who usually writes about AI, agentics, and the future of AI runtimes.

Your coding agent has auto-run enabled. It clones a third-party repository to evaluate a dependency, reads the README, and follows the setup instructions it finds there. Within minutes it has enumerated every cloud credential in the environment and pushed them to an endpoint it was told to call. The approval prompt you glanced at looked harmless.

That pattern now has a documented precedent. InfoQ reported in September 2026 on Wiz's "GhostApproval" finding: six AI coding assistants could be tricked by malicious repositories while showing a harmless-looking approval prompt. The attacker never touched your code. They wrote content the agent read and trusted.

This is why coding agents need different controls than standard application security. Static analysis and penetration testing assume a human writes the code and a human runs it. A coding agent does both, and it does so with its own credentials, its own network access, and no pause between deciding and executing. The attack lands on the agent's permissions, not on a bug in your logic.

This guide covers what AI code security means in 2026, why generated code is still insecure despite better models, the five attack vectors that target coding agents, and six controls in the order you should build them. It's written for engineering leaders who own the uptime and the breach when an agent goes wrong.

Key takeaways

  • Model capability hasn't fixed AI-generated code security: Newer models write syntactically correct code at roughly the same security pass rate as older ones.
  • Agents add execution risk: An assistant suggests code; an agent installs, runs, and commits it under its own identity.
  • Isolate first: Running agent code in a microVM caps the damage from every other failure.
  • Layer the rest: Least privilege, scanning, monitoring, and approval gates each close a path isolation leaves open.
  • Match control depth to autonomy: An agent that suggests code needs scanning; an agent that deploys needs all six controls.

What is AI code security?

AI code security is the practice of preventing, detecting, and containing vulnerabilities in code that AI models write, including the agents that install, run, and commit that code. The term also has a second meaning: using AI to find and fix vulnerabilities in any codebase, the way GitHub's Copilot Autofix and Google's CodeMender do. This guide focuses on the first meaning plus the agent execution layer, because that's where an insecure line becomes a breach.

Traditional application security assumes a human wrote the code and a human decides when it runs. When an agent does both, the risk profile shifts along three dimensions:

  1. Generated code at machine speed: Agents produce and commit code faster than human review scales. Vibe coding, where a developer accepts generated output without reading it, sits at the far end of the same curve.
  2. Autonomous decisions: The agent installs dependencies, edits configuration, and executes code without a human approving each step. Every one of those steps runs with the agent's credentials.
  3. New attack vectors: Prompt injection, rules-file poisoning, memory poisoning, and malicious Model Context Protocol (MCP) servers target the agent's instructions rather than your code's logic. A scanner never seesSome scanners can detect them, such as poisoned MCP tool descriptions.

The first two dimensions multiply a familiar problem. The third is new, and it's why the controls in this guide start at the execution layer rather than at the model.

Why does AI-generated code create security risk?

Veracode's 2026 GenAI Code Security Report puts a number on the gap. Across 100+ models tested over four years, the average security pass rate is 56%, and in Veracode's words it "hasn't moved". GPT-5.5 leads the Summer 2026 dataset at 68%, while six of the eleven newest models sit between 50% and 53%. The same models produce syntactically correct code nearly 100% of the time, so the output compiles, passes tests, and ships with the flaw intact. A model upgrade is not a security control. Treat AI output as untrusted input and build review and isolation around it.

A compromised agent rarely introduces one bug. Anthropic disclosed a state-sponsored group that manipulated Claude Code to infiltrate targets, with the agent performing 80–90% of the attack execution autonomously. That ratio inverts the traditional threat model: one agent with broad permissions does the work of a coordinated team. Review capacity has the opposite problem. Agents open pull requests faster than security teams can read them, a pressure SC Media describes as outpacing the programs meant to catch it. Reviewers end up choosing between rubber-stamping and stalling delivery.

The cost of getting it wrong keeps climbing. IBM's 2026 Cost of a Data Breach report puts the global average at $4.99 million, a 12% increase over the prior year and a record high. An agent holding deployment credentials is a direct path to that number.

Regulation adds a timeline. Under the EU AI Act, Article 99 sets fines of up to €35 million or 7% of global turnover for prohibited practices, with lower tiers of €15 million or 3% and €7.5 million or 1% for other violations. The Commission's implementation timeline, as amended by the Digital Omnibus, foresees the main application milestones by 2 August 2028. Teams that treat AI data governance as an afterthought end up retrofitting controls under deadline pressure instead of designing them in.

Common attack vectors against AI coding agents

Indirect prompt injection is an attack where instructions hidden in content the agent reads, such as a README, an issue comment, a web page, or a tool's output, get interpreted as commands. The user never types the malicious text. The agent encounters it while doing its job and follows it.

The vectors below either use that mechanism directly or exploit what the agent does after it has been steered:

  • Indirect prompt injection: Any content the agent ingests can carry instructions. The pandas-ai project's own issue tracker documents the failure mode: its default executor ran LLM-written code with full Python builtins and no sandbox, so an indirect injection became remote code execution.
  • Config and rules-file poisoning: Pillar Security found invisible Unicode characters in rules files steering GitHub Copilot and Cursor to insert backdoors that human reviewers couldn't see. An October 2026 arXiv paper extends the pattern to package hallucination triggered through injected AGENTS.md and CLAUDE.md files.
  • Dependency attacks: Snyk documented a weaponized Nx package whose postinstall script invoked local coding agents with unsafe flags to exfiltrate credentials. Slopsquatting is the newer variant: a USENIX Security '25 study of 16 LLMs and 576,000 samples found hallucinated package names in at least 5.2% of commercial-model outputs and 21.7% of open-source-model outputs, 205,474 unique names an attacker can register.
  • Tool and credential abuse: OWASP's Q1 2026 exploit round-up cites CVE-2025-59528, remote code execution through a CustomMCP configuration, and lists sandbox execution, config-input validation, and restricted outbound connectivity as the mitigations.
  • Memory poisoning across sessions: Tenable documented zero-click injections and poisoning that persists in agent memory across sessions, so one compromised interaction shapes every future run.

Every one of these ends the same way: the agent executes code it shouldn't, or it reaches a credential it shouldn't. That's why the controls below start with where code runs and what it can touch.

How to secure AI coding agents: six controls in priority order

These six controls draw on OWASP's Top 10 for Agentic Applications, the NIST AI Risk Management Framework (AI RMF), and the CSA MAESTRO Framework. Each closes a specific path from the vectors above. Isolation caps the damage, least privilege shrinks the prize, and the remaining four catch what slips through. The order below is the order to build in.

Not every agent needs every control at the same depth. The starting point depends on what the agent can do: more autonomy means a larger blast radius, which changes where the first engineering week goes. Find your agent type in the left column and work left to right. Numbers in parentheses match the control headings below.

Agent typeStart withAdd nextCan deferWhy first
Executes untrusted code in productionMicroVM isolation (1) + least privilege (2)Runtime monitoring (5) + scanning and review (3)Approval gates beyond deploy actions (6)A kernel escape or stolen credential is the worst outcome; isolation and scoped identity cap it
Commits code via PRs (human-reviewed)Scanning and review (3) + input/output and config checks (4)Least privilege (2) + audit logging (5)Full microVM isolation (1)Human review is already the gate; scanning keeps it from drowning
Suggests code only (no execution)Output filtering (4) + dependency scanning (3)Human approval gates (6)Runtime monitoring (5)Nothing executes, so the risk is what reaches the repository

If your agents execute code, isolation and least privilege are your highest-value controls. If they only commit code for human review, scanning and input validation give you the fastest risk reduction.

1. Run agent code in microVM-isolated sandboxes

For executing AI-generated or untrusted code, microVMs provide hardware-enforced isolation that containers cannot match. Containers share the host kernel, so one kernel bug is a single point of failure, and they expose the host's 300+ Linux system calls as attack surface. A microVM runs a dedicated kernel per workload. One process hosts each microVM, and the virtual machine monitor exposes only a handful of emulated devices, so an attacker who breaks the guest kernel still faces a hardware-supported boundary and a small amount of host-side code. The container escape record shows the shared-kernel boundary failing in practice: CVE-2025-23266 in NVIDIA's Container Toolkit scored CVSS 9 and was published in July 2025.

Teams can build this isolation boundary themselves or compare managed agent infrastructure platforms that provide microVM-based execution. Blaxel is one such option, using the same microVM approach as AWS Lambda. Sandboxes resume from standby in under 25 milliseconds, which supports the response times coding agents need. Delty provides one implementation example: its AI pull request reviews run on Blaxel so each customer's code executes in its own microVM rather than a shared container. Next step: audit where agent-generated code runs today. List every host, container, and CI runner that executes agent output, and mark which ones share a kernel with anything else.

2. Enforce least privilege and keep secrets out of the sandbox

Give each agent its own identity with the smallest permission set its task needs, and let credentials expire when the task ends. Microsoft's shared responsibility model for AI agents states it plainly: don't grant the agent a broad standing identity, and authorize every action. In practice that means short TTLs (15 minutes is a workable default), credentials scoped to one repository or one database, and a service identity that is never a human's login. GitHub applies the same principle to its Copilot cloud agent: it cannot approve a pull request created by the user who requested it, and pull requests opened under its own app identity need one more human approval.

Better still, keep secrets out of the sandbox entirely. One implementation of this pattern is Blaxel's proxy secrets injection, available in public preview, which inserts credentials at the egress proxy so agent code never sees a raw API key even when an injection succeeds. Next step: list every credential present in the agent's environment, including environment variables and mounted files, and remove any the current task doesn't require.

3. Scan and review AI-generated code at every stage

Treat every line the agent writes as an external contributor's first pull request. Run checks at four stages, because each catches a different failure:

  1. IDE: Scanning during generation flags insecure patterns before they're committed, which is the cheapest place to fix them.
  2. Pull request: Static analysis plus software composition analysis block known vulnerability classes and flag outdated, vulnerable, or nonexistent dependencies before merge.
  3. CI: A full-codebase scan, secret scanning, and a build that fails on critical findings.
  4. Deploy: A policy gate that blocks unscanned or unattested artifacts from reaching production.

Secret scanning earns its own line. GitGuardian's analysis of about 20,000 Copilot-active repositories found 6.4% leaked a secret, against 4.6% for public repositories overall. Java needs the most attention: Veracode's 2025 report measured a 72% security failure rate for AI-generated Java, the worst of the four languages tested, so Java teams should make static analysis a merge requirement rather than an advisory. CodeValet gives agents a queryable code-intelligence map of symbols and dependencies, which reduces context errors but doesn't replace a scanner.

4. Validate inputs, filter outputs, and treat agent config files as untrusted

Validate structured inputs with schemas, filter the unstructured content the agent ingests (issue comments, documentation, web pages, tool output), and check that outputs match the request. An agent asked to refactor a database query shouldn't return code that opens a network socket or writes to the filesystem. Scope checks like that catch both injection attempts and hallucinations that drift beyond the task. Indirect prompt injection has worked this way since Black Hat USA 2023 demonstrated it compromising production systems without direct interaction.

Extend the same distrust to the agent's own configuration. Rules files, AGENTS.md, CLAUDE.md, and MCP server definitions are inputs an attacker can write to, and the agent reads them with more authority than a README. Review them in pull requests like code, pin them to a reviewed version, and scan generated code for embedded secrets before it reaches the repository. Next step: add a CI check that fails on invisible Unicode characters in rules files, the technique Pillar Security found steering Copilot and Cursor.

5. Monitor runtime behavior and log every agent action

Static analysis catches known patterns; runtime monitoring catches novel behavior. Set baselines for normal activity and alert on deviations. If your agent typically makes five to 10 API calls per task and suddenly issues 200 with new network destinations, that deviation deserves a look before the task completes. Call frequency, egress destinations, and file access scope turn vague "anomaly detection" into alerting rules your team can act on.

Log every agent action, not only failures: prompt, tool call, parameters, and result. Store those logs outside the agent's environment so a compromised agent can't edit its own record. For cloud-level detection, AWS GuardDuty and Google Cloud Security Command Center cover the infrastructure layer. For agent-level visibility, platforms with built-in AI observability help; Blaxel includes OpenTelemetry-based tracing and logging across every sandbox execution, so you can tie a suspicious call to the task that triggered it. Next step: pick three metrics, record a week of baseline, and write one alert for each.

6. Add human approval gates for high-risk actions

Not every action needs sign-off. Operations with a large blast radius do: infrastructure changes, security-critical code paths, new external API integrations, database schema changes, and production deploys. Define these gates as policy-as-code so the agent can't route around them and the rule set gets reviewed like any other code. GitHub's Copilot cloud agent is a working example: its pull requests require human approval before CI/CD workflows run.

Gates also produce the record you need afterward. When an incident hits, your first question should be "what did the agent do in the 30 minutes before this?" Without durable logs linking each prompt, tool call, and code change to an approval decision, you're reconstructing the timeline from scattered sources under pressure. Log the full chain from request to decision to executed action. Next step: list every tool your agent can call, mark which ones can change production or move money, and put an approval in front of each.

Start with isolation, then layer the rest

Execute agent-generated code in isolation first, then add scoped credentials, scanning, monitoring, and approval gates in that order. The stakes are the credentials and production systems the agent can already reach: one poisoned repository or dependency turns developer velocity into credential theft across your stack.

For agents that execute generated or untrusted code, whether you build this execution boundary internally or choose among managed agent infrastructure platforms, verify that workloads run in separate microVMs, secrets remain outside the execution environment, and idle sandboxes can preserve state without compute charges. Blaxel is one option to evaluate against those criteria: each sandbox runs in its own microVM, remains in standby indefinitely at zero compute cost, and can use proxy secrets injection. For teams using OpenAI's stack, Blaxel is also a first-class sandbox provider in the OpenAI Agents SDK, with Blaxel Sandboxes handling the execution layer beneath OpenAI's Codex harness. The platform holds SOC 2 Type II and ISO 27001 certifications, and Health Insurance Portability and Accountability Act (HIPAA) compliance is available through a Business Associate Agreement. The Sandboxes documentation covers how LLM-generated code runs in sandboxed virtual machines.

FAQs about AI code security

Is AI-generated code secure?

No, not by default. Across the models Veracode has tested, roughly half of generated samples fail security tests, and that share hasn't moved as models improved. The code compiles and passes functional tests while skipping authorization checks, input validation, and safe defaults. Treat it like an external contributor's first pull request: scan it, review security-sensitive paths by hand, and never auto-merge.

Why do microVMs isolate better than containers for AI-generated code?

For AI-generated or untrusted code, the difference is what you're betting the boundary on. Containers share the host kernel, so isolation rests on namespaces, cgroups, and hardening, and a single kernel exploit collapses it. MicroVMs move the boundary to hardware virtualization with a separate kernel per workload. A bad dependency install becomes a sandbox incident instead of a host compromise. For your own trusted services, containers remain the industry standard.

How do you prevent prompt injection in AI coding agents?

You can't fully prevent it. Input filtering removes obvious payloads, but any content the agent reads is a potential instruction, and zero-click injections need no mistake from the user. Contain it instead: microVM isolation limits what an injected agent can reach, least privilege limits what it can take, and approval gates stop it from deploying or exfiltrating. Design on the assumption that any model can be injected.

What compliance frameworks apply to AI code security?

Most teams map controls to two buckets. For governance and accountability, use the NIST AI RMF. For technical verification, use OWASP AISVS, the OWASP Top 10 for Agentic Applications (published December 2025) for agent-specific risks like tool misuse and memory poisoning, and the CSA MAESTRO Framework for threat modeling. If your agent influences releases, treat it as change management too: durable logs from prompt to deploy, and human oversight for defined high-risk operations.

Related articles