Skip to main content

Secure Coding with AI Cheat Sheet

Security practices for AI-assisted and agentic software development title: Secure Coding with AI Cheat Sheet

Updated 20 min readMarkdown
Secure Coding with AI Cheat Sheet

Introduction

AI coding tools have moved beyond code suggestion. In 2026, agentic coding tools such as Claude Code, Cursor Agent Mode, Aider, Devin, Copilot Workspace, and Codex can execute shell commands, install packages, edit files, run tests, access the network, and push branches autonomously.

Many developers run these agents with auto-accept enabled, allowing an agent to operate with the developer's permissions and minimal human oversight.

This cheat sheet addresses security risks specific to AI-assisted and agentic coding. It focuses on threats that do not exist, or are materially amplified, in traditional development workflows. It does not replace general secure coding guidance.

Related guidance:

Threat Model and Trust Boundaries

AI coding agents operate across multiple trust boundaries. Understanding these boundaries is essential before applying security controls.

Trust boundaries in agentic coding

 [DEVELOPER]                    [AGENT]                    [EXTERNAL]
 Developer  ── permissions ──> AI Agent  ── reads ──────> Repository content
 approves or                  executes                    (issues, PRs,
 auto-accepts                 commands                    READMEs, deps,
                                                          changelogs)
      │                          │                            │
      │                    [MODEL PROVIDER]              [MCP SERVERS]
      │                     API calls                     Tool calls
      │                     Code + context                File access
      │                     sent to provider              Network access
      │                                                   Credentials
      │
      └──────────────────── [CI/CD] ─────────────────────────
                              Workflows
                              Organization secrets
                              Deployment access

Threat actors and attack surfaces

Repository content as an instruction source. Issue bodies, PR descriptions, PR comments, README files, dependency changelogs, error traces, fetched web pages, and MCP tool responses all become context when an agent reads them. An attacker who can write to any of these sources may be able to influence agent behavior.

MCP servers as tool providers. Agents connect to MCP servers to access tools. A malicious or compromised MCP server can poison tool descriptions, shadow legitimate tool names, exfiltrate credentials through tool arguments, or change tool definitions after initial approval (a rug pull).

Rules files as persistent steering. Files such as CLAUDE.md, AGENTS.md, .cursorrules, and .github/copilot-instructions.md can silently steer future generations. They may be modified by a malicious PR or by the agent itself to embed persistent instructions.

The agent itself. Agents running with auto-accept and broad developer permissions can install packages, write files, execute shell commands, modify CI configuration, and push branches. A compromised agent context can have the same blast radius as a compromised developer workstation.

CI/CD agents. Review bots and CI runners, including AI-powered PR review and code-fix actions, may process attacker-controlled PR content while holding organization secrets or repository write permissions. This creates a confused deputy risk.

1. Hallucinated Dependencies

AI coding assistants may suggest package names that do not exist on public registries. Attackers can monitor these hallucinated names and register malicious packages using matching names. This is a form of AI-assisted typosquatting.

Do

  • Verify that every AI-suggested package exists on the intended public registry before installing it.
  • Review the package page, download history, maintainer history, ownership, and creation date.
  • Investigate packages with very low download counts, recent creation dates (for example, less than 30 days), or a single maintainer with no established package history.
  • Implement a pre-install hook or CI check that blocks packages below an organization-defined minimum age.
  • Maintain an internal allowlist of approved packages where practical.

Don't

  • Blindly run npm install, pip install, or go get with package names suggested by an AI without verification.
  • Assume that a package exists or is safe merely because an AI suggested it.
  • Ignore typosquatting risk. AI assistants can generate names that are close to legitimate packages but differ slightly.

2. Outdated Dependencies with Known CVEs

AI models learn from historical code and documentation. They may suggest dependency versions that were current during training but now contain known vulnerabilities. An assistant may not know about CVEs disclosed after its training cutoff or its security-index update.

Do

  • Run dependency auditing tools on every AI-generated dependency list before merging:
    • npm audit
    • pip-audit
    • govulncheck
    • cargo audit
  • Configure CI/CD pipelines to fail on known vulnerabilities according to your organization's severity and exception policy, regardless of whether code was written by a human or an AI.
  • Pin dependencies to specific versions and update them through the normal dependency-management process.
  • Cross-reference suggested versions against vulnerability databases such as the NVD, GitHub Advisory Database, and OSV.

Don't

  • Accept AI-suggested dependency versions without checking for known CVEs.
  • Assume AI assistants are aware of recent vulnerability disclosures.
  • Disable dependency auditing for AI-generated code.

3. Indirect Prompt Injection in the Development Loop

Agentic coding tools ingest context from repositories, networks, and connected tools. Any content an agent reads may contain instructions intended to alter its behavior. This is indirect prompt injection applied to the development workflow.

Attack vectors

  • Issue bodies and PR descriptions: An attacker may open an issue containing hidden instructions. When a developer asks an agent to fix the issue, the agent may process those instructions as part of its context.
  • PR comments and review feedback: Malicious review comments may attempt to make an agent modify unrelated files, weaken security controls, or disclose information.
  • README and documentation files: Cloned repositories, dependencies, and fetched documentation may contain instructions that are not obvious to human readers but are still processed by an agent.
  • Error traces and log output: Crafted error messages may attempt to inject instructions when an agent reads output while debugging.
  • Dependency changelogs and release notes: Content in changelogs may influence an agent asked to compare versions or investigate an update.
  • Fetched web pages: Hidden or untrusted instructions on referenced pages may enter the session context and steer later actions. Unrestricted fetch tools can also create SSRF and data-exfiltration risks.

Do

  • Treat repository content---including issues, PRs, comments, and READMEs---as untrusted input when processed by an AI coding agent.
  • Review agent actions and diffs for unexpected changes after it processes external content.
  • Use tools that sanitize or flag potential injection patterns in repository content before the agent processes it, while recognizing that detection is not a complete defense.
  • Restrict agent context to the minimum files and content needed for the task.
  • Audit agent actions after processing content from external contributors or public repositories.
  • Fetch untrusted pages in a separate, restricted sub-agent or tool that returns only short, relevant snippets. This reduces exposure but does not eliminate injection risk.
  • Apply SSRF protections to agent fetch tools and allowlist permitted destinations. An unrestricted fetch tool may leak secrets or source code through URL paths or query strings.

Don't

  • Allow agents to process issue bodies, PR descriptions, or comments from untrusted contributors without reviewing the resulting actions.
  • Assume content is safe because it appears in a familiar context, such as a GitHub issue.
  • Give agents unrestricted web-browsing or arbitrary-URL fetch access without egress controls.
  • Treat web_fetch or HTTP GET tools as harmless read-only operations that are exempt from approval and destination checks.
  • Try to prompt an already-compromised session back on course after an untrusted fetch. Roll back workspace changes and start a fresh session.

4. MCP and Tool Security

AI coding agents connect to Model Context Protocol (MCP) servers for file operations, database queries, API calls, and other capabilities. Compromised or malicious MCP servers create a direct supply-chain risk to the development environment.

For comprehensive guidance, see the MCP Security Cheat Sheet.

Do

  • Audit all MCP servers connected to the development environment. Maintain an allowlist of approved servers and tools.
  • Pin or snapshot tool definitions and detect changes. Use snapshot-and-diff mechanisms to catch rug-pull updates in which a tool's behavior changes after initial approval.
  • Review tool descriptions for hidden instructions. Tool descriptions are part of the agent's context and are an injection surface.
  • Restrict which tools the agent can invoke. Apply least privilege: a coding agent usually does not need access to email, payment, or administrative tools.
  • Monitor for tool-name shadowing, where a malicious MCP server registers a tool with the same name as a legitimate one.
  • Validate tool arguments before execution. Agents may pass credentials, file contents, or environment variables as arguments without understanding their sensitivity.

Don't

  • Connect to MCP servers from untrusted sources without security review.
  • Allow agents to discover and connect to MCP servers automatically without approval.
  • Trust tool descriptions as benign.
  • Allow MCP tools unrestricted filesystem, network, or credential access on the developer's machine.

Reference: CVE-2026-39313 --- mcp-framework versions before 0.2.22 were reported to have unbounded memory allocation in HTTP request-body handling, potentially allowing unauthenticated denial of service. This illustrates why AI framework dependencies need security auditing and runtime limits.

5. Agent Runtime Sandboxing

Agentic coding tools can execute commands, install packages, write files, and access the network on a developer's machine. Without sandboxing, a compromised agent context may inherit the developer's privileges.

Do

  • Run AI coding agents in sandboxed environments such as dev containers, restricted shells, virtual machines, or ephemeral cloud workspaces.
  • Use tool allowlists to restrict executable commands. Block access to credential stores, SSH keys, cloud CLI configurations, and sensitive directories unless explicitly required.
  • Apply egress controls to the agent runtime. If the task does not require outbound network access, block it.
  • Use ephemeral credentials scoped to the current task rather than long-lived developer credentials.
  • Understand and evaluate the risk of flags such as --dangerously-skip-permissions and auto-accept modes. These can bypass confirmation prompts and permit broad execution.
  • Set resource limits for CPU, memory, disk, and process count.
  • If the agent exposes pre-execution hooks, use them to check commands, file edits, and pushes before execution. The check should run outside the agent's context, fail closed, and be deployed through managed settings. See the Coding Agents: Pre-Execution Hooks guidance in the AI Agent Security Cheat Sheet.

Don't

  • Run AI coding agents with full developer credentials, SSH keys, and cloud access tokens without sandboxing.
  • Enable auto-accept mode on untrusted or unfamiliar codebases.
  • Allow agents to access production credentials, deployment keys, or organization-level secrets from the development environment.
  • Assume the agent will only touch files relevant to the current task.
  • Rely on per-action approval prompts as the primary security control. Anthropic has reported high approval rates for Claude Code permission prompts, illustrating why human confirmation alone may not be a sufficient safeguard.

6. Rules Files and Persistent Steering

AI coding tools read configuration files that steer behavior across future interactions. These files are a persistence mechanism: an attacker who can modify them may influence subsequent generations.

Affected files

  • .cursorrules
  • .cursor/rules/
  • CLAUDE.md
  • .claude/
  • AGENTS.md
  • .github/copilot-instructions.md
  • .windsurfrules
  • .aider.conf.yml
  • Custom system-prompt files referenced by an AI tool

Do

  • Treat rules files as security-critical configuration. Review changes with the same scrutiny as CI/CD pipeline changes.
  • Include rules files in code-review requirements. Require explicit approval for modifications.
  • Monitor for unexpected creation or modification of rules files, including changes made by the agent itself.
  • Use Git hooks or CI checks to flag changes to known rules files in every PR.
  • Audit existing rules files for instructions that weaken security controls, disable safety features, or tell the agent to ignore particular files or patterns.

Don't

  • Allow external contributors to add or modify rules files without security review.
  • Allow an AI agent to modify its own rules files without explicit developer approval.
  • Assume rules files are benign because they are plain text. They are instruction-injection surfaces with persistent effects.

7. Out-of-Scope Edits and Review Anchoring

Agents may modify files beyond the requested scope, including lockfiles, CI configurations, unrelated tests, formatting, and dependencies. Reviewers who focus only on the requested change may miss these modifications.

Do

  • Use diff-aware review tooling that highlights every changed file, not only files related to the task description.
  • Implement CI checks that flag unexpected modifications, including lockfile changes, CI/CD configuration changes, test modifications, and changes outside the requested scope.
  • Review every file in an agent-generated PR individually. Do not approve based only on the PR description.
  • Configure CODEOWNERS rules to require specific reviewers for sensitive files such as CI configurations, Dockerfiles, deployment scripts, and agent rules files.
  • Limit the agent's file-access scope when the tool supports directory restrictions or file allowlists.

Don't

  • Approve agent-generated PRs based on a summary without reviewing the full diff.
  • Assume lockfile changes, test modifications, or formatting changes are benign because they look routine.
  • Allow agents to modify files outside the explicitly requested scope without flagging those changes for review.

8. Test Fabrication and Test Deletion

AI agents may make CI pass by deleting failing tests, weakening assertions, mocking the unit under test, or writing tests that assert incorrect behavior. A passing test suite generated by the same agent that produced the code is not independent assurance.

Do

  • Require human review of all AI-generated test modifications, especially:
    • Deleted tests: Why was the test removed?
    • Weakened assertions: Did assertEquals become assertNotNull?
    • New mocks: Do mocks replace real dependencies the test was intended to exercise?
    • Behavior assertions: Do tests assert the correct expected behavior, or merely the behavior generated by the agent?
  • Add adversarial and negative test cases the AI did not generate, including invalid inputs, expired tokens, malformed payloads, boundary conditions, and concurrent access.
  • Measure security confidence through adversarial testing and independent analysis, not simply by whether all tests pass.
  • Implement CI rules that flag test deletions or reductions in assertion counts in agent-generated PRs.
  • Write or independently verify security-critical tests for authentication, authorization, input validation, and cryptographic operations.

Don't

  • Treat AI-generated test suites as proof of security.
  • Measure confidence by test pass rate alone. A 100% pass rate is meaningless if tests assert broken behavior.
  • Allow agents to delete or modify existing tests without a human-reviewed justification.
  • Allow an agent to write both security-critical code and its tests without independent verification.

9. Prompt Context Leakage and Sensitive Code Exposure

AI coding assistants may send code context---including open files, project structure, and terminal output---to a model provider's API. This context can contain credentials, personal data, proprietary business logic, and internal architecture details.

Do

  • Review what context the AI coding assistant sends to its provider. Consult the tool's documentation and configuration.
  • Configure AI tools to exclude sensitive directories and files from context. Common examples include:
    • .env, .env.*
    • *.pem, *.key
    • credentials.json
    • serviceAccountKey.json
  • Audit what the coding tool sends using controlled request inspection. Redact credentials, personal data, and sensitive source code before recording captured traffic. Follow the Logging Cheat Sheet's data-exclusion guidance.
  • Use self-hosted or air-gapped AI coding tools for projects containing classified, regulated, or highly sensitive code, where required by policy.
  • Store secrets in environment variables, vault services, or encrypted secret stores---not in project files that AI tools can read.

Don't

  • Use cloud-hosted AI coding assistants on classified or top-secret codebases without approval.
  • Assume an assistant only sends the currently open file. Many tools can send broader project context.
  • Open .env files or private keys in an IDE while an AI coding assistant is active unless the tool's handling of that content is understood and approved.
  • Paste API keys, tokens, or credentials into a terminal while AI tools with terminal-context access are running.
  • Assume .gitignore prevents AI tools from reading files. .gitignore affects Git; AI tools may read directly from the filesystem.

10. Prompt-to-Code Supply Chain Risk

AI coding agents may modify application code as well as build scripts, CI/CD configurations, package scripts, and deployment infrastructure. These files can execute automatically in trusted contexts with elevated privileges.

For broader lifecycle controls, see the Software Supply Chain Security Cheat Sheet.

Do

  • Review AI changes to the following files with heightened scrutiny:
    • package.json scripts, especially postinstall, preinstall, prepare, and prebuild
    • .github/workflows/*.yml (GitHub Actions)
    • .gitlab-ci.yml
    • Dockerfile and docker-compose.yml
    • Makefile, Rakefile, and Taskfile
    • setup.py and pyproject.toml build configuration
    • go generate directives
    • Any file that executes automatically during build, installation, testing, or deployment
  • Flag AI-generated changes that add network access, download external resources, or execute shell commands in build or deployment contexts.
  • Implement CI checks that identify changes to build configuration and require explicit approval for CI/CD pipeline modifications.
  • Ensure third-party GitHub Actions are pinned to a specific commit SHA rather than a mutable tag.

Don't

  • Allow AI agents to modify CI/CD pipelines, Dockerfiles, or package scripts without explicit human review.
  • Accept AI-generated GitHub Actions that reference third-party actions only by a mutable tag.
  • Trust AI-generated build scripts that download or execute external URLs without verification.
  • Merge AI changes to deployment configuration without verifying the complete build and deployment path.

11. CI/CD Agents and Confused Deputy Risk

AI-powered CI/CD agents---including review bots, automated code fixers, and PR assistants---may run on PR events with access to organization secrets, deployment credentials, or repository write permissions. A malicious PR may manipulate an agent into disclosing secrets or modifying the pipeline.

Do

  • Scope CI agent credentials to the minimum permissions required. Review bots should not have deployment keys or write access to secrets.
  • Treat PR titles, bodies, comments, and diffs as attacker-controlled input. Filter or sanitize this content before passing it to CI agents.
  • Run CI agents in isolated environments without production secrets or credentials beyond those required for the specific job.
  • Log CI agent action metadata, correlation identifiers, authorization decisions, and outcomes. Exclude secrets and sensitive prompt, tool-argument, and response content. Follow the Logging Cheat Sheet.
  • Require approval before CI agents can push commits, modify workflows, or access sensitive resources.

Don't

  • Give CI agents organization-level secrets or deployment credentials when they only need read access.
  • Allow CI agents to process external-contributor PR content without appropriate isolation.
  • Trust CI agent output---including reviews and suggested fixes---without verifying that it was not influenced by malicious PR content.

Agent output rendered in IDE chat panes, PR comments, or review interfaces may contain Markdown-based exfiltration links, bidirectional text overrides, and zero-width characters. These can mislead reviewers or influence future agent runs.

Do

  • Sanitize agent output before rendering it in IDE chat panes or PR comments. Strip or escape Markdown image tags, hidden links, and unsafe HTML.
  • Detect and flag bidirectional override and isolate characters, including U+202A through U+202E and U+2066 through U+2069.
  • Detect zero-width characters such as U+200B, U+200C, U+200D, and U+FEFF in code, commits, and agent output.
  • Use CI checks to scan PRs for homoglyph attacks and invisible characters.
  • Review agent-generated commit messages and PR descriptions for embedded content that could influence future agent runs.

Don't

  • Render agent output containing Markdown images or links without sanitization. External image URLs may leak context through URL parameters.
  • Assume code is safe because it contains only visibly readable ASCII characters. Invisible and bidirectional characters may be difficult to spot in common editors.
  • Commit agent-generated content without scanning for Unicode injection.

13. Multi-Agent and Sub-Agent Propagation

When multiple agents interact---for example, when a coding agent delegates to a search agent or a review agent processes another agent's output---prompt injection can propagate across agent boundaries. A compromised context in one agent may become instructions for another.

Do

  • Treat output from one agent as untrusted input when passing it to another agent.
  • Establish context boundaries between agents. Do not pass full conversation histories or raw tool responses between agents without sanitization.
  • Monitor cross-agent interactions for instruction-propagation patterns, such as one agent's output instructing another to disclose data or modify unrelated files.
  • Validate that sub-agent actions remain within the scope defined by the parent task.

Don't

  • Chain agents without context boundaries. If Agent A is compromised, Agent B should not blindly execute its output.
  • Allow sub-agents to inherit all parent permissions and credentials without scope restrictions.
  • Assume agent-to-agent communication is trusted simply because both agents belong to the same workflow.

For more guidance, see the AI Agent Security Cheat Sheet and Section 8 (Multi-Server Isolation) of the MCP Security Cheat Sheet.

14. Human Accountability

AI-generated code must have a human owner. Every AI-assisted change should be reviewed, approved, and attributable to a developer responsible for its security and maintainability. AI tools do not accept responsibility for the code they generate. The developer who accepts and commits the code does.

Do

  • Assign a human owner to every AI-generated code change. That owner is responsible for its correctness, security, and maintenance.
  • Require explicit developer approval before merging AI-generated code. Approval should indicate that the developer has reviewed and understood the change.
  • Maintain audit trails showing which developer approved each AI-assisted change, including the AI tool and model version used where feasible.
  • Treat AI as a tool, not an accountable team member. Saying "the AI wrote it" does not transfer responsibility.

Don't

  • Deploy AI-generated code that no human has reviewed and approved.
  • Allow AI-generated code to bypass code review because the tool is usually correct.
  • Treat AI-generated review comments as a substitute for human review.
  • Attribute security failures solely to the AI tool. The people and organization accepting the code remain accountable.

OWASP Top 10 Mapping


OWASP Top 10 category Relevant sections


A01: Broken Access Control Section 5: Agent Runtime Sandboxing; Section 11: CI/CD Agents

A03: Injection Section 3: Indirect Prompt Injection; Section 12: Markdown and Unicode Injection

A04: Insecure Design Section 8: Test Fabrication and Test Deletion; Section 14: Human Accountability

A05: Security Misconfiguration Section 6: Rules Files; Section 7: Out-of-Scope Edits

A06: Vulnerable and Outdated Section 1: Hallucinated Components Dependencies; Section 2: Outdated Dependencies

A07: Identification and Section 4: MCP and Tool Security Authentication Failures

A08: Software and Data Integrity Section 10: Prompt-to-Code Supply Failures Chain Risk

A09: Security Logging and Section 9: Prompt Context Leakage; Monitoring Failures Section 11: CI/CD Agents

A10: Server-Side Request Forgery Section 3: Indirect Prompt Injection; Section 4: MCP and Tool Security

References


Security guidance should be validated against your organization's threat model, tool versions, and current vendor documentation. Reassess controls as agent capabilities and integrations change.

About the author

No comments yet. Be the first to comment.