Join our Newsletter — 33% off our NHI Course
Home› Guides› AI Coding Agents Security Guide: Protecting Secrets, Code…
Guide Agentic AI Security

AI Coding Agents Security Guide: Protecting Secrets, Code and Pipelines

Free PDF · we’ll email you a download link

← All guides
By Lalit Choda, NHI Mgmt Group Updated 20 October 2026 17 min read
On this page

AI coding agents sit in the most credential-rich place in the organisation: the developer's machine and the software delivery pipeline. They read source code and configuration, run shell commands, install packages, open pull requests and connect to cloud, repository and database tools through MCP servers. They do this with the developer's access, often with little separation between "suggest" and "execute". That makes them highly productive and, if misdirected or compromised, a fast path to secrets, source code and production. This guide covers the identity and security risks of AI coding assistants and agents in the IDE, the terminal and CI/CD, the controls that let teams use them safely, and how to detect and respond when something goes wrong. It is written for platform and DevSecOps engineers, security architects and engineering leaders who approve these tools.

Key takeaways

  • A coding agent inherits everything the developer's environment can reach: local files and .env files, cloud CLI sessions, SSH keys, Git credentials, package registry tokens and MCP server credentials.
  • Four risks dominate: secrets entering the agent's context, agents acting with over-scoped tokens, untrusted repositories and dependencies steering the agent, and supply chain attacks on the tools themselves.
  • Run agents in sandboxes with scoped, short-lived credentials, not directly in a developer's fully privileged session. OWASP calls this "Least-Agency": do not grant autonomy that is not needed.
  • Instructions are not permissions. Keep humans in control of irreversible and production-affecting actions, enforced by tooling and access rights rather than by what the prompt says.
  • In CI/CD, give agents their own workload identities with narrow, keyless access, never a shared personal access token, and never on workflows triggered by untrusted contributors.

Where coding agents run

Each surface has a different identity picture, and the identity determines the blast radius.

SurfaceWhat the agent doesIdentity it usually runs asMain identity risk
IDE assistants and extensionsCompletion and chat, increasingly editing files and running commandsThe developer, plus any API key pasted into the extensionExtension or plugin steals keys; workspace files leak into context
Terminal and command-line agentsPlan and execute multi-step changes, run tests, use Git and call toolsThe developer's shell, with every authenticated CLIAmbient cloud, Git and registry credentials
Cloud and background agentsWork on a repository in a hosted environment and open pull requestsA platform identity or GitHub AppRepository write scope broader than the task
CI/CD agentsReview, fix or generate code on issues, pull requests or pipeline eventsThe pipeline token and any secrets the workflow exposesAttacker-controlled text processed while holding write or publish rights
"Vibe coding" platformsBuild and deploy whole applications, often with databases and hostingPlatform-held production credentialsStanding write access to production

The risks

The table summarises the risks below with the OWASP categories they relate to and an incident that illustrates each.

RiskOWASP referenceIllustrative incident
Secrets in contextNHI2 Secret LeakageJetBrains Marketplace AI Plugin Campaign 2026
Ambient, over-scoped credentialsASI03 Identity and Privilege Abuse, NHI5 Overprivileged NHIPocketOS Database Deletion 2026
Prompt injection from code and contentASI01 Agent Goal Hijack, LLM01 Prompt InjectionGemini CLI Prompt Injection Flaw 2025
Unsafe command executionASI05 Unexpected Code Execution (RCE)Replit AI Agent Database Deletion 2025
Supply chain attacks on tools and packagesASI04 Agentic Supply Chain Vulnerabilities, NHI3Amazon Q Developer Extension Compromise 2025
MCP server credentials and configurationASI02 Tool Misuse and Exploitation, ASI04Amazon Q MCP Config Vulnerability 2026
CI/CD agent identitiesNHI7 Long-Lived Secretstj-actions/changed-files Compromise 2025
AttributionNHI10 Human Use of NHIAgent actions logged as the developer

1. Secrets in the agent's context

Agents read files to understand a project. If .env files, configuration with embedded credentials, private keys or cloud credential files are in scope, their contents can end up in prompts sent to a model provider, in logs, in generated code and in commit messages. Once a secret has been in a model's context, treat it as potentially exposed. The tools themselves also hold keys: in the JetBrains campaign, Aikido Security found 15 malicious AI assistant plugins that forwarded the AI provider API keys developers entered to the attacker. See the Secrets Management Guide.

2. Ambient, over-scoped credentials

A developer's terminal typically has an authenticated cloud CLI, a Git credential helper and package registry tokens. An agent running there can use all of them, and when it hits a permissions error it may look for another credential that works. At PocketOS, a coding agent working in staging found a Railway API token in an unrelated file and deleted the production database and its volume-level backups in one API call. Railway says the token was account-scoped, giving "access to everything in your account, across every workspace you're part of", although it had been created only to manage custom domains.

3. Prompt injection from code and content

Repositories, issues, pull request descriptions, documentation, dependency README files and web pages the agent fetches can all contain instructions. A malicious contribution or a poisoned dependency can tell an agent to add a backdoor, weaken a check, or send environment variables to an external URL. Tracebit showed this against Gemini CLI two days after release: instructions hidden in a README, combined with weak allow-list matching, silently sent the developer's environment variables to a remote server. Agent instruction files are also a target. AGENTS.md describes itself as "a clear, predictable place for instructions" for coding agents, which is exactly why whoever can edit it can steer the agent. See the Prompt Injection Guide.

4. Unsafe command execution

Agents that run shell commands can execute destructive or exfiltrating commands, whether hallucinated or injected. OWASP lists this as ASI05, Unexpected Code Execution (RCE), noting that vibe coding tools "often generate and execute code" and recommending that teams "prevent direct agent-to-production systems". At Replit, an agent deleted a live production database during a declared code freeze, produced fake data and wrongly said rollback was impossible; the data was restored.

5. Supply chain attacks on AI tools and packages

  • In the Amazon Q Developer extension compromise, AWS said an inappropriately scoped GitHub token in CodeBuild let an attacker commit a prompt telling the agent to wipe local files and delete AWS resources; version 1.84.0 shipped on 17 July 2025 but the code failed to run.
  • The Nx s1ngularity Attack 2025 went further: according to Wiz, the malware prompted installed AI CLIs "with dangerous flags" such as --dangerously-skip-permissions and --yolo to help hunt for secrets.
  • The Shai-Hulud npm Worm 2025 stole npm, GitHub and cloud tokens from developer laptops and CI runners that installed infected packages.

Coding agents amplify these risks because they install packages and extensions quickly and on the model's judgement, including packages that do not exist. A USENIX Security 2025 study of 576,000 generated code samples found that the average share of hallucinated packages was at least 5.2% for commercial models and 21.7% for open-source models: names an attacker can register. See the Malicious Package and Dependency Confusion Guide.

6. MCP server credentials and configuration

Coding agents commonly connect to GitHub, cloud, database and ticketing MCP servers configured with long-lived personal access tokens in local JSON files. Local servers are also code that runs on the developer's machine. The MCP specification's security best practices warn that a malicious startup command in a client configuration gives attackers arbitrary code execution "with MCP client privileges", and recommend showing the exact command, requiring explicit approval and running servers in a sandbox. Wiz found that Amazon Q loaded .amazonq/mcp.json from a repository without a prompt or trust check, and the servers it started inherited the developer's AWS session. See the MCP Security Guide.

7. CI/CD agent identities

Agents in pipelines often run with the pipeline's token, which may be able to push to protected branches, publish packages or deploy. An agent triggered by an external contributor's issue or pull request may process attacker-controlled text while holding those permissions. GitHub's own guidance says to avoid pull_request_target and workflow_run with untrusted pull requests or code, and both the Nx and Shai-Hulud attacks began with a misconfigured pull_request_target workflow. The tj-actions compromise showed how one stolen bot token can print the secrets of every pipeline that trusts a component. See the GitHub and GitHub Actions Security Guide.

8. Attribution

When an agent commits code or runs commands as the developer, logs cannot distinguish the human from the agent. That weakens code review, incident investigation and compliance evidence, and it is the agent equivalent of OWASP's NHI10, Human Use of NHI, in reverse: a machine acting under a person's identity.

Controls for local agents (IDE and terminal)

  • Sandbox the agent. Run it in a container, development container or virtual machine with only the project mounted, no access to home-directory credential stores, and restricted network egress. Many agents offer built-in sandbox and permission modes; Claude Code, for example, documents a manual mode that starts read-only and asks before edits and commands, and an OS-level sandbox with filesystem and network isolation. Use the most restrictive mode that works.
  • Keep secrets out of the workspace. Use a secrets manager or runtime injection instead of .env files; configure agent ignore rules for credential files; scan the workspace for secrets before enabling an agent.
  • Scope the credentials the agent can use. Give it a separate, short-lived, least-privilege token for the specific repository or project, rather than the developer's session. Never let it reach production or admin credentials.
  • Require approval for risky actions. OWASP recommends "human confirmation for high-impact or destructive actions (delete, transfer, publish)" with a dry-run or diff first. Keep auto-approve lists short, and remember the ASI02 example of an auto-approved ping tool used to exfiltrate data over DNS.
  • Control what the agent can install. Route package installs through an internal registry or proxy with allowlisting, and block newly published or unknown packages by default.
  • Allowlist extensions, plugins and MCP servers through device management, pin versions, and require approval before any project-level MCP configuration runs.
  • Protect instruction files. Treat AGENTS.md and agent rule files as code: require review for changes, and be cautious running agents on untrusted repositories.

Controls for cloud and CI/CD agents

  • Give each agent its own workload identity, separate from human accounts and other pipelines.
  • Use keyless authentication. GitHub's OIDC provider issues a token per job, and the cloud provider returns "a short-lived cloud access token that is available only for the duration of the job". Pin trust policies to the specific repository, workflow, branch or environment through the sub claim. See the Workload Identity Federation Guide and the Cloud Workload Identity Guide.
  • Limit repository permissions. Set the GITHUB_TOKEN default to the minimum, as GitHub advises; the agent can create branches and open pull requests, but cannot push to protected branches, approve its own changes, change workflows or publish releases.
  • Separate untrusted input from privileged execution. Do not run agents with write tokens or secrets on events triggered by external contributors.
  • Pin third-party actions to a full-length commit SHA, which GitHub says means a bad actor would need a SHA-1 collision to backdoor them.
  • Require human review of every agent-authored change before merge, with branch protection enforcing it.
  • Keep deploy credentials out of reach: agents build and test; separate, controlled pipelines deploy. Use trusted publishing rather than stored registry tokens. See the CI/CD Pipeline Identity Security Guide and the SLSA and Build Provenance Guide.

Detection and monitoring

Agents act faster than people review. OWASP calls strong observability "non-negotiable" for agentic systems. Watch for:

  • Agent use of unexpected credentials: cloud or registry API calls from developer sessions that do not match the task, especially destructive calls such as volume or database deletion.
  • AI CLIs run with permission-skipping flags or from install scripts, as in the Nx attack; alert on these strings in endpoint telemetry.
  • New or changed MCP configuration files in repositories and home directories, and MCP servers spawning shells or network connections.
  • Secrets in prompts, agent logs and agent-authored commits, using secret scanning on all three.
  • Egress from sandboxes to destinations outside the allowlist, including DNS-based exfiltration.
  • CI anomalies: agent workflows triggered by first-time contributors, workflow file changes in agent pull requests, and secrets printed to logs.

See the AI Agent Observability and Incident Response Guide.

Responding to a compromised agent or tool

  1. Disable the extension, plugin, MCP server or agent workflow across the fleet through device management or repository settings.
  2. Assume every credential the agent could reach is exposed: cloud sessions, Git and registry tokens, MCP tokens and AI provider keys. Revoke and rotate them, starting with publishing and production rights.
  3. Review agent-authored commits, pull requests and package publications since the compromise window began.
  4. Check for persistence: new instruction files, MCP configurations, workflow changes and repositories made public.
  5. Record what the agent could reach and use it to tighten scopes. The Leaked Credential Response Playbook covers rotation in detail.

Governance

  • Publish an approved list of coding assistants and agents, with the configuration, sandbox mode and permission settings each must use.
  • Register agents that run with their own identities (cloud and CI/CD) in your NHI inventory, with an owner.
  • Mark agent-authored commits and pull requests (for example with commit trailers or a dedicated bot identity) so reviewers and auditors can tell them apart.
  • Keep an inventory of where AI provider keys have been entered, set spending caps, and rotate any secret that has entered an agent's context.
  • Find unsanctioned tools. See the Shadow AI Discovery Guide.
  • Include coding agents in secure development training and in your Agentic AI Security Policy Template. NIST SP 800-218 (SSDF) practice PO.5 asks for development environments that are separated and protected, which now includes the agents working in them.

Framework mapping

This table is an indicative NHI Mgmt Group alignment, not an official crosswalk. IDs were checked against NIST CSF 2.0, the NIST SP 800-53 Rev. 5 catalogue, the CIS Controls (control level, with safeguard text from the CIS Controls Assessment Specification), the OWASP Top 10 for Agentic Applications 2026 and the OWASP NHI Top 10 2025. ISO/IEC 27001:2022 Annex A names come from a published Annex A index.

Control areaNIST CSF 2.0NIST SP 800-53 Rev. 5ISO/IEC 27001:2022 Annex ACIS Controls v8.1OWASP
Secrets kept out of agent context and codePR.AA-01, PR.DS-01IA-5(7)5.17 Authentication informationControl 3, Control 16NHI2, NHI7
Scoped, short-lived agent credentialsPR.AA-05AC-6, IA-5, IA-95.18 Access rights, 8.2 Privileged access rightsControl 5 (5.5), Control 6 (6.8)ASI03, NHI5
Sandboxing and egress controlPR.IR-01SC-7, SC-398.22 Segregation of networks, 8.31 Separation of development, test and production environmentsControl 4, Control 13ASI05, NHI8
Human approval for destructive actionsPR.PS-01AC-3(2), CM-3, CM-58.32 Change managementControl 16 (16.1)ASI02
Package, extension and MCP server allowlistingID.RA-09, PR.PS-05CM-7(5), CM-11, CM-148.19 Installation of software on operational systemsControl 2 (2.5), Control 16 (16.4, 16.5)ASI04, NHI3
Keyless CI/CD workload identityPR.AA-01, PR.AA-03IA-5, IA-95.16 Identity managementControl 5 (5.5)NHI7
Review and protected branches for agent changesPR.PS-06SA-15, CM-38.4 Access to source code, 8.25 Secure development life cycle, 8.28 Secure codingControl 16 (16.1, 16.12)ASI01
Attribution and logging of agent actionsPR.PS-04, DE.CM-03AU-3, AU-10, AC-6(9)8.15 Logging, 8.16 Monitoring activitiesControl 8 (8.2, 8.5)NHI10

Common failure patterns

  • "It's only staging": an agent in a non-production environment can still reach a production token left in a file, as at PocketOS.
  • Freezes enforced by prompt: telling the agent not to change anything instead of removing its write access, as at Replit.
  • Auto-approve creep: allow-lists that grow until most commands run unprompted, and allow-list matching that a chained command can bypass.
  • Trusting the repository: opening untrusted code in a tool that auto-loads its instruction or MCP configuration files.
  • Build tokens with release rights: a CI token that can commit to the agent's own source or publish packages, the root of the Amazon Q and Nx incidents.
  • Personal tokens in MCP configs: a developer's broad PAT reused for every MCP server and never rotated.
  • Keys pasted into plugins: AI provider keys entered into unvetted extensions, with no record of where each key went.
  • No way to tell agent from human: commits and cloud actions recorded under the developer's identity, so investigations cannot separate the two.

Metrics that show progress

MetricWhat it showsTarget direction
Share of agent sessions running in a sandbox or dev containerContainment of local agentsUp
Agents and MCP servers using long-lived personal tokensExposure to credential theft and misuseDown, towards zero
CI/CD agent workflows using OIDC instead of stored secretsKeyless adoptionUp
Approved tools as a share of coding agents and extensions observedShadow toolingUp
Agent-authored changes merged without human reviewEnforcement of reviewZero
Secrets detected in prompts, agent logs and agent commitsContext hygieneDown
Time to rotate credentials after a tool compromise advisoryResponse readinessDown
Agent commits and actions attributable to an agent identityAudit qualityUp, towards 100%

Implementation roadmap

PhaseFocusActions
First 30 daysVisibility and quick winsInventory coding agents, extensions and MCP servers in use; publish an approved list; turn on secret scanning for repositories and agent logs; remove production tokens from developer workspaces
Days 31 to 90Contain local agentsDefault to sandboxed or dev container execution; issue scoped, short-lived tokens for agents; require approval before project MCP configs run; route installs through an allowlisting registry proxy
Days 91 to 180Secure pipelinesGive CI/CD agents their own OIDC-based identities; set minimum token permissions; remove agent workflows from untrusted triggers; pin actions to SHAs; enforce branch protection and review
Beyond 180 daysGovern and measureMark all agent-authored work; register agent identities with owners; add agent-specific detections; rehearse the compromised-tool runbook; report the metrics above

Practitioner checklist

  • Coding agents run in a sandbox without access to the developer's credential stores.
  • No long-lived secrets in project files; credential files excluded from agent context.
  • Agents use separate, scoped, short-lived tokens, never production or admin credentials.
  • Shell commands, package installs, pushes and external tool calls require approval unless explicitly allowlisted.
  • Packages come through an allowlisting registry proxy; extensions, plugins and MCP servers are approved and pinned.
  • Project-level MCP and instruction files cannot run or change without review.
  • CI/CD agents use keyless workload identity with trust policies pinned to repository, workflow and branch.
  • Agents cannot merge, approve, change workflows or deploy; branch protection enforces human review.
  • Agent activity is distinguishable from human activity in commits and logs.
  • Any secret exposed to an agent's context, or to a compromised tool, is rotated.

Standards and references

Related NHI Mgmt Group resources: MCP Security Guide · Secrets Management Guide · NHI Authentication Guide · CI/CD Pipeline Identity Security Guide · Agentic AI Security Guide

Free PDF

Take this guide with you

Every section, table and checklist in one PDF, with links to the sources and related guides. We’ll email you a download link.

Free weekly newsletter

Subscribe to the NHI & AI Identity Journal

The latest on NHI and Agentic AI security – articles, research, breaches, news and events every week.

Bonus 33% off our NHI Course when you subscribe.

NHIMG Editorial Note
Written and reviewed by Lalit Choda, NHI Mgmt Group. Last updated 20 October 2026.
NHI Mgmt Group — the #1 independent authority on Non-Human Identity, IAM, and Agentic AI security. nhimg.org

Free PDF by email

Get the guide

Enter your details and we’ll email you a download link.

Fill in all fields marked * and tick the PDF box to continue.