Skip to content

Secure Coding with AI Cheat Sheet / 使用AI的编码安全速查表

Introduction / 介绍

AI coding tools have moved beyond code suggestion. In 2026, agentic coding tools (Claude Code, Cursor agent mode, Aider, Devin, Copilot Workspace, Codex) 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, meaning the agent operates with the developer's full permissions and minimal human oversight.

AI编码工具已超越代码建议。到2026年,代理编码工具(Claude Code、Cursor代理模式、Aider、Devin、Copilot Workspace、Codex)可以自主执行shell命令、安装包、编辑文件、运行测试、访问网络和推送分支。许多开发者以自动接受的方式运行这些代理,这意味着代理以开发者的全部权限和最小的人类监督运行。

This cheat sheet addresses the security risks specific to AI-assisted and agentic coding. It focuses on threats that do not exist in traditional development workflows and does not restate general secure coding guidance already covered elsewhere.

本速查表针对AI辅助和代理编码特有的安全风险。它关注的是在传统开发工作流程中不存在的威胁,并且不会重复已在其他地方涵盖的一般安全编码指南。

For general secure coding, see the Secure Coding Practices Quick Reference Guide. For AI agent security beyond coding tools, see the AI Agent Security Cheat Sheet. For prompt injection prevention, see the LLM Prompt Injection Prevention Cheat Sheet. For MCP protocol security, see the MCP Security Cheat Sheet.

有关一般安全编码,请参阅安全编码实践快速参考指南。有关编码工具之外的AI代理安全,请参阅AI代理安全速查表。有关提示注入预防,请参阅LLM提示注入预防速查表。有关MCP协议安全,请参阅MCP安全速查表。

Threat Model and Trust Boundaries / 威胁模型和信任边界

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

AI编码代理跨越多个信任边界。在应用任何控制措施之前,理解这些边界是至关重要的。

                    TRUST BOUNDARIES IN AGENTIC CODING

 [DEVELOPER]                    [AGENT]                    [EXTERNAL]
  Developer  ──── permissions ──── AI Agent  ──── reads ──── Repo Content
  approves        (often full       executes       ingests     (issues, PRs,
  or auto-        dev access)       commands       context     READMEs, deps,
  accepts                                                      changelogs)
      |                |                |                |
      |           [MODEL PROVIDER]      |          [MCP SERVERS]
      |            API calls            |           Tool calls
      |            Code + context       |           File access
      |            sent to provider     |           Network access
      |                                 |           Credentials
      |                                 |
      |              [CI/CD]            |
      |            Workflows            |
      |            Org secrets          |
      |            Deploy access        |

Threat Actors and Attack Surfaces / 威胁行为者和攻击面

  • Repository content as instruction source. Issue bodies, PR descriptions, PR comments, README files, dependency changelogs, error traces, fetched web pages, and MCP tool responses all become instructions when the agent reads them. An attacker who can write to any of these can influence agent behavior.
    中文:存储库内容作为指令来源。当代理读取时,问题正文、PR描述、PR评论、README文件、依赖项变更日志、错误跟踪、获取的网页和MCP工具响应都成为指令。任何可以写入这些内容的攻击者都可以影响代理的行为。
  • 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 update tool definitions after initial approval (rug-pull).
    中文:MCP服务器作为工具提供者。代理连接到MCP服务器以访问工具。恶意或被入侵的MCP服务器可以毒化工具描述,影射合法工具名称,通过工具参数泄露凭证,或在初始批准后更新工具定义(地毯式撤回)。
  • Rules files as persistent steering. Files like .cursorrules, CLAUDE.md, AGENTS.md, .github/copilot-instructions.md, and .windsurfrules silently steer every future generation. They can be modified by a malicious PR or by the agent itself to embed persistent instructions.
  • The agent itself. Agents running with auto-accept and full developer permissions can install packages, write to any file, execute shell commands, modify CI configuration, and push branches. A compromised agent context has the same blast radius as a compromised developer workstation.
    中文:代理本身。运行带有自动接受和完整开发者权限的代理可以安装包、写入任何文件、执行shell命令、修改CI配置以及推送分支。被入侵的代理上下文具有与被入侵的开发者工作站相同的破坏半径。
  • CI/CD agents. Review bots and CI runners (e.g. claude-code-action, Copilot review) act on PR content with access to org secrets. A malicious PR can trigger the CI agent to exfiltrate secrets or modify the build pipeline. This is confused deputy at scale.

Section 1: Hallucinated Dependencies / 第1节:幻觉依赖

AI coding assistants frequently suggest package names that do not exist on public registries. Attackers monitor these hallucinated names and register malicious packages with matching names (AI-assisted typosquatting).

AI编码助手经常建议在公共注册表中不存在的包名。攻击者监控这些幻觉名称,并注册与恶意包名称匹配的恶意包(AI辅助的域名劫持)。

Do / 做

  • Verify every AI-suggested package exists on the public registry before installing. Check the package page, download count, maintainer history, and creation date.
    中文:在安装之前验证每个AI建议的包是否存在于公共注册表中。检查包页面、下载次数、维护者历史和创建日期。
  • Be suspicious of packages with very low download counts, recent creation dates (less than 30 days), or a single maintainer with no other packages.
    中文:对下载次数非常低、创建日期最近(少于30天)或只有一个没有其他包的维护者的包持怀疑态度。
  • Implement a pre-install hook or CI check that blocks installation of packages below a minimum age threshold.
    中文:实施一个预安装钩子或CI检查,阻止安装低于最小年龄阈值的包。
  • Maintain an internal allowlist of approved packages for your organization.
    中文:维护一个组织内部批准的包的允许列表。

Don't / 不

  • Blindly run npm install, pip install, or go get with package names suggested by an AI without verification.
    中文:盲目运行 npm install、pip install 或 go get,使用人工智能建议的包名而未经验证。
  • Assume that because an AI suggested a package, it exists or is safe.
    中文:假设因为人工智能建议了一个包,它就存在或安全。
  • Ignore typosquatting risk. AI assistants frequently suggest names that are close to real packages but slightly different.
    中文:忽略仿冒风险。人工智能助手经常建议与真实包名称相似但略有不同的名称。

Section 2: Outdated Dependencies with Known CVEs / 第2节:已知CVE的过时依赖项

AI models are trained on historical code. They frequently suggest dependency versions that were current during training but now have known vulnerabilities. The AI may not know about CVEs published after its training cutoff or after the coding tool's last security-index update.

人工智能模型是在历史代码上训练的。它们经常建议在训练期间是当前版本的依赖项版本,但现在存在已知漏洞。人工智能可能不知道在其训练截止日期之后或编码工具最后安全索引更新之后发布的CVE。

Do / 做

  • Run dependency auditing tools (npm audit, pip audit, govulncheck, cargo audit) on every AI-generated dependency list before merging.
    中文:在合并之前,在人工智能生成的依赖项列表上运行依赖项审计工具(npm audit、pip audit、govulncheck、cargo audit)。
  • Configure CI/CD pipelines to fail on known vulnerabilities in dependencies, regardless of whether the code was human-written or AI-generated.
  • Pin dependencies to specific versions and update them through your normal dependency management process, not through AI suggestions.
    中文:将依赖项固定到特定版本,并通过正常的依赖项管理流程更新它们,而不是通过人工智能建议。
  • Cross-reference AI-suggested versions against vulnerability databases (NVD, GitHub Advisory Database, OSV).
    中文:将人工智能建议的版本与漏洞数据库(NVD、GitHub安全公告数据库、OSV)进行交叉引用。

Don't / 不

  • Accept AI-suggested dependency versions without checking for known CVEs.
    中文:接受AI推荐的依赖版本,无需检查已知CVE漏洞。
  • Assume that AI assistants are aware of recent vulnerability disclosures.
    中文:假设AI助手了解最新的漏洞披露信息。
  • Disable dependency auditing for AI-generated code.
    中文:禁用AI生成代码的依赖审计。

Section 3: Indirect Prompt Injection in the Development Loop / 第3节:开发循环中的间接提示注入

Agentic coding tools ingest context from the repository, the network, and connected tools. Any content the agent reads can contain hidden instructions that alter its behavior. This is indirect prompt injection applied to the development workflow.

代理编码工具从仓库、网络和连接的工具中获取上下文。代理读取的任何内容都可能包含改变其行为的隐藏指令。这是应用于开发工作流程的间接提示注入。

Attack Vectors / 攻击向量

  • Issue bodies and PR descriptions. An attacker opens an issue containing hidden instructions. When a developer asks the agent to "fix issue #123", the agent reads the issue body and follows the embedded instructions.
    中文:问题主体和PR描述。攻击者打开包含隐藏指令的问题。当开发者要求代理“修复问题#123”时,代理会读取问题主体并遵循嵌入的指令。
  • PR comments and review feedback. Malicious review comments can instruct the agent to modify unrelated files, weaken security controls, or exfiltrate code when the developer asks the agent to "address review feedback."
    中文:PR评论和审查反馈。恶意审查评论可以指示代理修改无关文件、削弱安全控制或当开发者要求代理“处理审查反馈”时泄露代码。
  • README and documentation files. Cloned repositories, dependencies, and fetched documentation can contain instructions invisible to human readers but parsed by the agent.
    中文:README和文档文件。克隆的仓库、依赖和获取的文档可能包含对人类读者不可见但对代理可解析的指令。
  • Error traces and log output. When an agent reads error output to debug a failure, crafted error messages can inject instructions.
    中文:错误跟踪和日志输出。 当代理读取错误输出以调试失败时,精心设计的错误消息可以注入指令。
  • Dependency changelogs and release notes. Agents reading changelogs to understand version differences can be influenced by injected content.
    中文:依赖变更日志和发布说明。 读取变更日志以了解版本差异的代理可能会受到注入内容的影响。
  • Fetched web pages. Agents with web access can be influenced by content on pages they are asked to reference.
    中文:获取的网页。 具有网络访问权限的代理可能会受到他们被要求引用的页面上的内容的影响。

Do / 做

  • Treat all repository content (issues, PRs, comments, READMEs) as untrusted input when processed by an AI coding agent.
    中文:在 AI 编码代理处理时,将所有存储库内容(问题、PR、评论、README)视为不受信任的输入。
  • Review agent output for unexpected changes after the agent processes any external content.
    中文:代理处理任何外部内容后,审查代理输出以查找意外变化。
  • Use tools that sanitize or flag potential injection patterns in repository content before the agent processes it.
    中文:使用工具在代理处理之前对存储库内容中的潜在注入模式进行清理或标记。
  • 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.
    中文:在处理来自外部贡献者或公共存储库的内容后,审计代理操作。

Don't / 不

  • Allow agents to process issue bodies, PR descriptions, or comments from untrusted contributors without review of the agent's resulting actions.
    中文:允许代理处理来自不受信任贡献者的未审查的问题正文、PR 描述或评论。
  • Assume that content an agent reads is safe because it appears in a familiar context (e.g. a GitHub issue).
    中文:假设代理读取的内容是安全的,因为它出现在熟悉的环境中(例如 GitHub 问题)。
  • Give agents unrestricted access to browse the web or fetch arbitrary URLs without egress controls.
    中文:给予代理无限制的访问权限以浏览网页或抓取任意 URL,而不受出口控制。

Section 4: MCP and Tool Security / 第 4 部分:MCP 和工具安全

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

AI 编码代理连接到 MCP(模型上下文协议)服务器以访问文件操作、数据库查询、API 调用等工具。受损害或恶意的 MCP 服务器是开发环境的直接供应链风险。

For comprehensive MCP security guidance, see the MCP Security Cheat Sheet.

有关全面的 MCP 安全指南,请参阅 MCP 安全速查表。

Do / 做

  • Audit all MCP servers connected to your development environment. Maintain an allowlist of approved servers and tools.
    中文:审计连接到您的开发环境的所有 MCP 服务器。维护一份批准的服务器和工具的白名单。
  • Pin tool definitions and detect changes. Use snapshot-and-diff mechanisms to catch rug-pull updates where a tool's behavior changes after initial approval.
    中文:固定工具定义并检测更改。使用快照和差异机制来捕获在初始批准后工具行为发生变化的撤回更新。
  • Review tool descriptions for hidden instructions. Tool descriptions are part of the agent's context and can contain prompt injection payloads.
    中文:审查工具描述中的隐藏指令。工具描述是代理上下文的一部分,可能包含提示注入有效载荷。
  • Restrict which tools the agent can invoke. Apply least privilege -- a coding agent 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 to intercept calls.
    中文:监控工具名称的阴影问题,恶意MCP服务器可能会注册与合法工具同名以拦截调用。
  • Validate tool arguments before execution. Agents may pass sensitive data (credentials, file contents, environment variables) as tool arguments without awareness of the data classification.
    中文:在执行前验证工具参数。代理可能会在不了解数据分类的情况下,将敏感数据(凭证、文件内容、环境变量)作为工具参数传递。

Don't / 不

  • Connect to MCP servers from untrusted sources without security review.
    中文:未经安全审查,从不受信任的来源连接到MCP服务器。
  • Allow agents to discover and connect to MCP servers automatically without approval.
    中文:允许代理自动发现和连接到MCP服务器,无需批准。
  • Trust tool descriptions as benign. They are an injection surface.
    中文:信任工具描述为良性。它们是注入的表面。
  • Allow MCP tools unrestricted filesystem, network, or credential access on the developer's machine.
    中文:允许MCP工具在开发者的机器上无限制地访问文件系统、网络或凭证。

Reference: CVE-2026-39313 -- mcp-framework before 0.2.22: unbounded memory allocation in HTTP request body handling allowed unauthenticated denial of service. Example of a vulnerability in AI framework code that highlights the need for dependency auditing and runtime limits.

参考:CVE-2026-39313 -- mcp-framework 0.2.22 之前版本:在处理 HTTP 请求体时存在未限制的内存分配,允许未经身份验证的服务拒绝攻击。这是 AI 框架代码中一个漏洞的示例,突出了依赖项审计和运行时限制的必要性。

Section 5: Agent Runtime Sandboxing / 第5节:代理运行时沙箱

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

代理编码工具在开发者的机器上执行命令、安装包、写入文件和访问网络。如果没有沙箱,被破坏的代理上下文将具有与开发者相同的权限。

Do / 做

  • Run AI coding agents in sandboxed environments: dev containers, restricted shells, virtual machines, or ephemeral cloud workspaces.
    中文:在沙箱环境中运行 AI 编码代理:开发容器、受限外壳、虚拟机或短暂的云工作空间。
  • Use tool allowlists that restrict which commands the agent can execute. Block access to credential stores, SSH keys, cloud CLI configurations, and sensitive directories.
    中文:使用允许列表工具限制代理可以执行的命令。阻止对凭证存储、SSH 密钥、云 CLI 配置和敏感目录的访问。
  • Apply egress controls on the agent's runtime. If the agent does not need outbound network access for the current task, block it.
    中文:在代理的运行时应用出口控制。如果代理当前任务不需要出站网络访问,则阻止它。
  • Use ephemeral credentials scoped to the current task rather than long-lived developer credentials.
    中文:使用针对当前任务的短暂凭证,而不是长期开发者凭证。
  • Understand and evaluate the risk of flags like --dangerously-skip-permissions or auto-accept modes. These bypass confirmation prompts and give the agent unrestricted execution.
    中文:了解和评估 --dangerously-skip-permissions 或自动接受模式等标志的风险。这些标志绕过确认提示,并给予代理无限制的执行权限。
  • Set resource limits (CPU, memory, disk, process count) on agent execution environments.
    中文:在代理执行环境中设置资源限制(CPU、内存、磁盘、进程数)

Don't / 不

  • Run AI coding agents with your full developer credentials, SSH keys, and cloud access tokens without sandboxing.
    中文:使用您的完整开发者凭据、SSH密钥和云访问令牌运行AI编码代理,无需沙箱隔离
  • Enable auto-accept mode on untrusted or unfamiliar codebases.
    中文:在不受信任或不熟悉的代码库上启用自动接受模式
  • Allow agents to access production credentials, deployment keys, or org-level secrets from the development environment.
    中文:允许代理从开发环境访问生产凭据、部署密钥或组织级别的机密
  • Assume the agent will only touch files relevant to the current task.
    中文:假设代理只会接触与当前任务相关的文件

Section 6: Rules Files and Persistent Steering / 第六节:规则文件和持久化引导

AI coding tools read configuration files that steer their behavior across all future interactions. These files are a persistence mechanism -- an attacker who can modify them controls every subsequent generation.

AI编码工具读取配置文件,以引导它们在所有未来交互中的行为。这些文件是持久化机制——任何可以修改它们的攻击者将控制后续的所有生成

Affected Files / 受影响文件

  • .cursorrules, .cursor/rules/
  • CLAUDE.md, .claude/
  • AGENTS.md
  • .github/copilot-instructions.md
  • .windsurfrules
  • .aider.conf.yml
  • Custom system prompt files referenced by any AI tool
    中文:任何AI工具引用的自定义系统提示文件

Do / 做

  • Treat rules files as security-critical configuration. Review changes to these files with the same scrutiny as CI/CD pipeline changes.
  • Add rules files to your code review requirements. Require explicit approval for any modification.
    中文:将规则文件添加到您的代码审查要求中。任何修改都需要明确批准。
  • Monitor for unexpected rules file creation or modification, including by the agent itself.
    中文:监控意外创建或修改规则文件的情况,包括由代理自身引起的。
  • Use git hooks or CI checks that flag changes to known rules files in every PR.
    中文:使用git钩子或CI检查来标记每个PR中已知规则文件的更改。
  • Audit existing rules files for instructions that weaken security controls, disable safety features, or direct the agent to ignore certain file types or patterns.
    中文:审计现有规则文件,查找削弱安全控制、禁用安全功能或指示代理忽略某些文件类型或模式的说明。

Don't / 不

  • Allow PRs from external contributors to add or modify rules files without security review.
    中文:允许外部贡献者添加或修改规则文件,无需进行安全审查。
  • Allow the AI agent itself to modify its own rules files without explicit developer approval.
    中文:允许AI代理本身修改其规则文件,无需明确的开发者批准。
  • Assume rules files are benign because they are plain text. They are instruction injection surfaces with session-level persistence.
    中文:假设规则文件是良性的,因为它们是纯文本。它们是带有会话级持久性的指令注入表面。

Section 7: Out-of-Scope Edits and Review Anchoring / 第七节:范围外编辑和审查锚定

Agents routinely touch files beyond the scope of the requested change: lockfiles, CI configurations, unrelated tests, formatting changes, and dependency updates. Reviewers anchored on the requested change miss these modifications. This is the most common review failure mode in agentic coding.

代理通常会触及请求更改范围之外的文件:锁文件、CI配置、无关的测试、格式更改和依赖项更新。基于请求更改的审查者会错过这些修改。这是代理编码中最常见的审查失败模式。

Do / 做

  • Use diff-aware review tooling that highlights all files changed, not just the ones relevant to the task description.
    中文:使用具有差异感知的审查工具,突出显示所有更改的文件,而不仅仅是与任务描述相关的文件。
  • Implement CI checks that flag unexpected file modifications: lockfile changes, CI/CD config changes, test modifications, and changes to files outside the requested scope.
  • Review every file in an agent-generated PR individually. Do not approve based on the PR description alone.
    中文:单独审查代理生成的PR中的每个文件。不要仅根据PR描述进行批准。
  • Set up CODEOWNERS rules that require specific reviewers for sensitive files (CI configs, Dockerfiles, deployment scripts, rules files).
    中文:设置CODEOWNERS规则,要求对敏感文件(CI配置、Dockerfile、部署脚本、规则文件)指定特定审查者。
  • Limit the agent's file access scope when possible. Some tools support directory restrictions or file allowlists.
    中文:尽可能限制代理的文件访问范围。一些工具支持目录限制或文件允许列表。

Don't / 不

  • Approve agent-generated PRs based on the summary or description without reviewing the full diff.
    中文:基于摘要或描述批准代理生成的PR,而无需审查完整的差异。
  • Assume that 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.
    中文:允许代理在不标记这些更改以供审查的情况下修改明确请求范围之外的文件。

Section 8: Test Fabrication and Test Deletion / 第8节:测试伪造和测试删除

AI agents make CI green by deleting failing tests, weakening assertions, mocking the unit under test instead of fixing the code, or asserting the buggy behavior. A passing test suite generated by the same agent that produced the code provides no independent assurance.

AI代理通过删除失败的测试、削弱断言、模拟被测试的单元而不是修复代码,或断言有缺陷的行为,使CI测试结果为绿色。由生成代码的同一代理生成的通过测试套件不提供独立的保证。

Do / 做

  • Require human review of all AI-generated test modifications, with focus on:
    中文:要求对所有AI生成的测试修改进行人工审查,重点包括:
    • Deleted tests (why was this test removed?)
      中文:删除的测试(为什么删除了这个测试?)
    • Weakened assertions (did assertEquals become assertNotNull?)
      中文:弱化断言(assertEquals 是否变成了 assertNotNull?)
    • New mocks that replace real dependencies the test was designed to exercise
      中文:新的模拟对象,用于替换测试设计时旨在测试的真实依赖项
    • Tests that assert the generated behavior rather than the correct behavior
      中文:断言生成行为而不是正确行为
  • Add adversarial and negative test cases that the AI did not generate: invalid inputs, expired tokens, malformed payloads, boundary conditions, concurrent access.
    中文:添加AI未生成的对抗性和负面测试用例:无效输入、过期令牌、畸形有效载荷、边界条件、并发访问
  • Measure security confidence by adversarial testing results and independent analysis, not by "all tests pass."
    中文:通过对抗性测试结果和独立分析来衡量安全信心,而不是通过“所有测试通过”
  • Implement CI rules that flag test deletions or assertion-count reductions in agent-generated PRs.
    中文:实现CI规则,标记代理生成的PR中的测试删除或断言计数减少
  • Write security-critical tests manually for authentication, authorization, input validation, and cryptographic operations.
    中文:手动编写安全关键测试,用于身份验证、授权、输入验证和加密操作

Don't / 不

  • Trust AI-generated test suites as evidence of security.
    中文:将AI生成的测试套件视为安全证据
  • Measure confidence by test pass rate alone. 100% passing means nothing if the tests assert broken behavior.
    中文:仅通过测试通过率来衡量信心。如果测试断言了已损坏的行为,100%的通过率毫无意义。
  • Allow agents to delete or modify existing tests without explicit justification reviewed by a human.
    中文:允许代理在未经人类审查的明确理由下删除或修改现有测试。
  • Allow the agent to both write the security-critical code and its tests without independent verification.
    中文:允许代理在不进行独立验证的情况下编写安全关键代码及其测试。

Section 9: Prompt Context Leakage and Sensitive Code Exposure / 第9节:提示上下文泄露和敏感代码暴露

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

AI编码助手将代码上下文(打开的文件、项目结构、终端输出)发送到模型提供商的API。此上下文可能包含凭证、个人数据、专有业务逻辑和内部架构细节。

Do / 做

  • Review what context your AI coding assistant sends to the provider. Most tools document this.
    中文:审查您的AI编码助手发送给提供商的上下文。大多数工具都有文档记录这一点。
  • Configure AI tools to exclude sensitive directories from context. Add .env, .env.*, *.pem, *.key, credentials.json, serviceAccountKey.json, and similar sensitive files to your AI tool's context exclusion list (.cursorignore, .copilotignore, or equivalent).
    中文:配置AI工具以排除敏感目录的上下文。将.env、.env.*、*.pem、*.key、credentials.json、serviceAccountKey.json和类似敏感文件添加到AI工具的上下文排除列表(.cursorignore、.copilotignore或等效)。
  • Audit what your AI coding tool sends using controlled request inspection. Exclude or redact credentials, personal data, and sensitive source code before recording captured traffic; follow the Logging Cheat Sheet data exclusions.
    中文:使用受控请求检查审计您的AI编码工具发送的内容。在记录捕获的流量之前,排除或删除凭证、个人数据和敏感源代码;遵循日志作弊表数据排除。
  • Use self-hosted or air-gapped AI coding tools for projects handling classified, regulated, or highly sensitive code.
    中文:使用自托管或断网 AI 编码工具处理涉及机密、受监管或高度敏感代码的项目。
  • Store all secrets in environment variables, vault services, or encrypted secret stores -- never in files within the project tree where AI tools can read them.
    中文:将所有机密存储在环境变量、密钥库服务或加密的密钥存储中 -- 永远不要存储在项目树中的文件中,AI 工具可以读取它们。

Don't / 不

  • Use cloud-hosted AI coding assistants on classified or top-secret codebases without approval.
    中文:未经批准,不要在涉及机密或绝密代码库上使用云托管 AI 编码助手。
  • Assume that AI coding assistants only send the current file. Many send broader project context.
    中文:假设 AI 编码助手只发送当前文件。许多助手会发送更广泛的项目上下文。
  • Open .env files or private keys in your IDE while an AI coding assistant is active. The file contents may be sent as context.
    中文:当 AI 编码助手处于活动状态时,在您的 IDE 中打开 .env 文件或私钥。文件内容可能作为上下文发送。
  • Paste API keys, tokens, or credentials into your terminal while AI tools with terminal context access are running.
    中文:当运行具有终端上下文访问权限的 AI 工具时,将 API 密钥、令牌或凭证粘贴到您的终端中。
  • Assume that .gitignore prevents AI tools from reading files. .gitignore only affects git -- AI tools read from the filesystem directly.
    中文:假设 .gitignore 阻止 AI 工具读取文件。.gitignore 只影响 git -- AI 工具直接从文件系统中读取。

Section 10: Prompt-to-Code Supply Chain Risk / 第 10 部分:提示到代码供应链风险

See the Software Supply Chain Security Cheat Sheet for controls throughout the development lifecycle.

查看软件供应链安全速查表,了解整个开发生命周期中的控制措施。

AI coding agents modify not just application code but also build scripts, CI/CD configurations, package scripts, and deployment infrastructure. Changes to these files execute automatically in trusted contexts with elevated privileges.

AI编码代理不仅修改应用程序代码,还修改构建脚本、CI/CD配置、包脚本和部署基础设施。这些文件的更改将在具有提升权限的受信任环境中自动执行。

Do / 做

  • Review AI changes to the following files with heightened scrutiny -- treat them as security-critical:
    中文:以更高的关注度审查以下文件的AI更改——将其视为安全关键项:
    • package.json (scripts section: postinstall, preinstall, prepare, prebuild)
      中文:package.json(脚本部分:postinstall、preinstall、prepare、prebuild)
    • .github/workflows/*.yml (GitHub Actions)
    • .gitlab-ci.yml
    • Dockerfile, docker-compose.yml
    • Makefile, Rakefile, Taskfile
    • setup.py, pyproject.toml (build scripts)
      中文:setup.py、pyproject.toml(构建脚本)
    • go generate directives
      中文:go generate 指令
    • Any file that executes automatically during build, install, test, or deploy
      中文:在构建、安装、测试或部署过程中自动执行的任何文件
  • Flag any AI-generated change that adds network access, downloads external resources, or executes shell commands in build/deploy context.
  • Implement CI checks that diff build configuration files and require explicit approval for changes to CI/CD pipelines.
  • Ensure AI-generated GitHub Actions reference third-party actions pinned to a specific commit SHA, not a mutable tag.
    中文:确保 AI 生成的 GitHub Actions 引用第三方动作时,使用特定的提交 SHA 而不是可变的标签

Don't / 不

  • Allow AI to modify CI/CD pipelines, Dockerfiles, or package scripts without explicit human review.
  • Accept AI-generated GitHub Actions that reference third-party actions by tag without SHA pinning.
    中文:接受 AI 生成的 GitHub Actions,其中引用第三方动作时没有 SHA 锁定
  • Trust AI-generated build scripts that download or execute external URLs.
    中文:信任 AI 生成的构建脚本,它们下载或执行外部 URL
  • Merge AI changes to deployment configurations without verifying what changed in the build/deploy path.
    中文:在未验证构建/部署路径中更改的情况下合并 AI 变更到部署配置。

Section 11: CI/CD Agents and Confused Deputy Risk

AI-powered CI/CD agents (review bots, automated code fixers, PR assistants) run on PR events with access to org secrets, deployment credentials, and write access to the repository. A malicious PR can manipulate the CI agent into exfiltrating secrets or modifying the pipeline.

AI 驱动的 CI/CD 代理(审查机器人、自动代码修复器、PR 助手)在 PR 事件上运行,具有访问 org 秘密、部署凭证以及写入仓库的权限。恶意 PR 可以操纵 CI 代理泄露秘密或修改管道

Do / 做

  • Scope CI agent credentials to the minimum required permissions. Review bots should not have deploy keys or write access to secrets.
    中文:将 CI 代理凭证限制在所需的最小权限范围内。审查机器人不应有部署密钥或对秘密的写入访问
  • Filter and sanitize PR content (title, body, comments, diff) before passing it to CI agents as context. PR content is attacker-controlled input.
    中文:在将 PR 内容(标题、正文、评论、diff)传递给 CI 代理作为上下文之前进行过滤和清理。PR 内容是攻击者控制的输入
  • Run CI agents in isolated environments with no access to production secrets or credentials beyond what the specific job requires.
    中文:在隔离环境中运行 CI 代理,使其无法访问生产机密或凭证,仅限于特定工作所需的内容。
  • Log CI agent action metadata, correlation identifiers, authorization decisions, and outcomes. Exclude secrets and sensitive prompt, tool-argument, and response content; apply the Logging Cheat Sheet. Monitor for unexpected file modifications, network calls, or secret access patterns.
    中文:记录 CI 代理操作元数据、关联标识符、授权决策和结果。排除机密和敏感提示、工具参数和响应内容;应用日志记录作弊表。监控意外的文件修改、网络调用或机密访问模式。
  • Implement approval gates before CI agents can push commits, modify workflows, or access sensitive resources.
    中文:在 CI 代理可以推送提交、修改工作流或访问敏感资源之前,实施批准门。

Don't / 不

  • Give CI agents org-level secrets or deployment credentials when they only need read access.
    中文:当 CI 代理只需要读取访问时,授予其组织级别的机密或部署凭证。
  • Allow CI agents to process PR content from external contributors without sandboxing.
    中文:允许 CI 代理处理外部贡献者的 PR 内容,无需沙箱隔离。
  • Trust CI agent output (comments, reviews, suggested fixes) without verifying that the agent was not influenced by malicious PR content.
    中文:信任 CI 代理的输出(评论、审查、建议的修复),而不验证代理是否受到恶意 PR 内容的影响。

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

在 IDE 聊天窗格、PR 评论或审查界面中渲染的代理输出可以包含基于 Markdown 的数据泄露链接、双向(双向)文本覆盖和零宽字符,这些会影响未来的代理行为或误导审查者。

Do / 做

  • Sanitize agent output before rendering in IDE chat panes or PR comments. Strip or escape Markdown image tags, hidden links, and HTML entities.
    中文:在IDE聊天面板或PR评论中渲染代理输出之前进行清理。删除或转义Markdown图片标签、隐藏链接和HTML实体。
  • Detect and flag bidi override characters (U+202A through U+202E, U+2066 through U+2069) and zero-width characters (U+200B, U+200C, U+200D, U+FEFF) in code, commits, and agent output.
    中文:检测并标记代码、提交和代理输出中的双向重写字符(U+202A至U+202E,U+2066至U+2069)和零宽度字符(U+200B,U+200C,U+200D,U+FEFF)。
  • Use CI checks that scan for homoglyph attacks and invisible characters in PRs.
    中文:使用CI检查扫描PR中的同形攻击和不可见字符。
  • Review agent-generated commit messages and PR descriptions for embedded content that could influence future agent runs.
    中文:审查代理生成的提交消息和PR描述中可能影响未来代理运行的嵌入式内容。

Don't / 不

  • Render agent output containing Markdown images or links without sanitization. Image tags with external URLs can exfiltrate conversation context via URL parameters.
    中文:渲染未进行清理的包含Markdown图片或链接的代理输出。带有外部URL的图片标签可以通过URL参数泄露对话上下文。
  • Assume that code containing only visible ASCII characters is safe. Zero-width and bidi characters are invisible in most editors.
    中文:假设只包含可见ASCII字符的代码是安全的。零宽度和双向字符在大多数编辑器中是不可见的。
  • Allow agent-generated content to be committed without scanning for unicode injection.
    中文:允许提交由代理生成的内容而不扫描Unicode注入。

Section 13: Multi-Agent and Sub-Agent Propagation / 第13节:多代理和子代理传播

When multiple agents interact (e.g. a coding agent delegates to a search agent, or a review agent processes output from a coding agent), prompt injection can propagate across agent boundaries. A compromised context in one agent becomes instructions for the next.

当多个代理交互时(例如,编码代理将任务委托给搜索代理,或审查代理处理编码代理的输出),提示注入可以在代理边界之间传播。一个代理的受损害上下文成为下一个代理的指令。

Do / 做

  • Treat output from one agent as untrusted input when passed to another agent.
    中文:将一个代理的输出视为未经验证的输入,当传递给另一个代理时。
  • Implement context boundaries between agents. Do not pass full conversation history or raw tool responses between agents without sanitization.
    中文:在代理之间实施上下文边界。不要在未经清理的情况下在代理之间传递完整的对话历史或原始工具响应。
  • Monitor cross-agent interactions for instruction propagation patterns (e.g. one agent's output instructing another to exfiltrate data or modify 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 Agent A's output.
    中文:在不设置上下文边界的情况下链式连接代理。如果代理A被破坏,代理B不应盲目执行代理A的输出。
  • Allow sub-agents to inherit the full permissions and credentials of the parent agent without scope restriction.
    中文:允许子代理继承父代理的全部权限和凭据,而不受范围限制。
  • Assume that agent-to-agent communication is trusted because both agents are "your" tools.
    中文:假设代理之间的通信是可信的,因为这两个代理都是“你的”工具。

For comprehensive guidance on multi-agent trust boundaries, see the AI Agent Security Cheat Sheet and the MCP Security Cheat Sheet Section 8 (Multi-Server Isolation).

关于多代理信任边界的全面指南,请参阅AI代理安全速查表和MCP安全速查表第8节(多服务器隔离)

Section 14: Human Accountability / 第14节:人类问责制

AI-generated code must have a human owner. Every AI-assisted change should be reviewed, approved, and attributable to a developer who is 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.

AI生成的代码必须有人类所有者。每个AI辅助的变更都应经过审查、批准,并归因于对其安全性和可维护性负责的开发者。AI工具不对生成的代码承担责任。接受并提交代码的开发者负责。

Do / 做

  • Assign a human owner to every AI-generated code change. That owner is responsible for its correctness, security, and maintenance.
    中文:为每个AI生成的代码变更分配一个人类所有者。该所有者负责其正确性、安全性和维护性。
  • Require explicit developer approval before merging any AI-generated code. The approval indicates the developer has reviewed and understood the change.
    中文:在合并任何AI生成的代码之前,要求明确的开发者批准。批准表明开发者已审查并理解了变更。
  • Maintain audit trails showing which developer approved which AI-generated changes, including the AI tool and model version used.
    中文:保持审计跟踪,显示哪些开发者批准了哪些AI生成的变更,包括使用的AI工具和模型版本。
  • Treat AI as a tool, not a colleague. A developer who says "the AI wrote it" is still responsible for it.
    中文:将AI视为工具,而非同事。声称“AI写了它”的开发者仍需对此负责。

Don't / 不

  • Deploy AI-generated code that no human has reviewed and approved.
    中文:部署未经人类审查和批准的AI生成的代码。
  • Allow AI-generated code to bypass code review because "the AI is usually right."
    中文:允许人工智能生成的代码绕过代码审查,因为“人工智能通常是对的。”
  • Treat AI approval (e.g. AI-generated code review comments) as a substitute for human review.
    中文:将人工智能的批准(例如,人工智能生成的代码审查评论)视为人类审查的替代品。批准代码的开发者负有责任。
  • Attribute security failures to the AI tool. The developer who approved the code is accountable.
    中文:将安全漏洞归咎于人工智能工具。批准代码的开发者负有责任。

OWASP Top 10 Mapping / OWASP Top 10 映射

OWASP Top 10 Relevant Section / 相关部分
A01: Broken Access Control
A01: 破坏访问控制
Section 5: Agent Runtime Sandboxing, Section 11: CI/CD Agents
第5节:代理运行时沙箱,第11节:CI/CD 代理
A03: Injection
A03: 注入
Section 3: Indirect Prompt Injection, Section 12: Markdown and Unicode Injection
第3节:间接提示注入,第12节:Markdown 和 Unicode 注入
A04: Insecure Design
A04: 不安全设计
Section 8: Test Fabrication, Section 14: Human Accountability
第8节:测试伪造,第14节:人类责任
A05: Security Misconfiguration
A05:安全配置错误
Section 6: Rules Files, Section 7: Out-of-Scope Edits
第6节:规则文件,第7节:超出范围的编辑
A06: Vulnerable and Outdated Components
A06:易受攻击和过时的组件
Section 1: Hallucinated Dependencies, Section 2: Outdated Dependencies
第1节:幻觉依赖,第2节:过时依赖
A07: Identification and Authentication Failures
A07:身份验证和识别失败
Section 4: MCP and Tool Security
第 4 部分:MCP 和工具安全
A08: Software and Data Integrity Failures
A08:软件和数据完整性失败
Section 10: Prompt-to-Code Supply Chain Risk
第 10 部分:提示到代码供应链风险
A09: Security Logging and Monitoring Failures
A09:安全日志和监控失败
Section 9: Prompt Context Leakage, Section 11: CI/CD Agents
第九节:提示上下文泄露,第十一节:CI/CD 代理
A10: Server-Side Request Forgery
A10:服务器端请求伪造
Section 3: Indirect Prompt Injection, Section 4: MCP and Tool Security
第三节:间接提示注入,第四节:MCP 和工具安全

References / 参考