AI command-line tools run with the developer's own file access, so every .env file, cloud credential and token on the workstation is one instruction away from the model's context, a command line or an outbound request. Two pieces of 2026 research made this concrete. In October, Adversa AI showed a single crafted web page steering GitHub Copilot CLI in autopilot mode into reading a .env.prod file and sending its contents to an outside endpoint. In November, Apiiro researchers reported that standing command approvals saved by Claude Code had put 2,539 secrets into public repositories. This guide explains how terminal agents reach local secrets, how those secrets leave the machine, and which settings and habits close each path in Claude Code, Gemini CLI and GitHub Copilot CLI.
For how .env files and environment variables work in general and safer ways to deliver secrets to applications, see Environment Variables and .env Files. This page is about the terminal agent as the reader and carrier of those secrets.
Key takeaways
- GitHub states plainly that Copilot has the same access as you do to files on your computer. The same is true of any terminal agent running as your user unless you sandbox it.
- Secrets leave in three main ways: injected instructions that make the agent read and send them, the agent echoing them into commands or files that are later shared, and saved configuration files that end up in commits or packages.
- The Copilot CLI research needed autopilot mode, a permissive model and a single fetched URL, and completed in about 28 seconds. Reducing autonomy where the agent reads untrusted content is the most direct control.
- Claude Code saves "Yes, and don't ask again" approvals as allow rules in
.claude/settings.local.json. If an approved command contained a password, the password is now in that file. - Each tool provides its own controls: deny rules for file reads, tool allow and deny flags, trusted directories and sandboxes. Use them, but also remove secrets from the places agents work.
- The durable fix is fewer local secrets: short-lived credentials, secrets managers with runtime retrieval and no plain text passwords in shell commands.
How terminal agents reach local secrets
A terminal agent combines a model with tools: read and write files, run shell commands, fetch URLs and call MCP servers. Each tool runs under the developer's operating system account. That gives the agent several routes to secrets that never had to be "given" to it:
- Project files.
.env,.env.local,.env.prod,config/*.yml, Terraform variable files and test fixtures with real keys. - Home directory credentials. Cloud CLI credential files, Kubernetes config, SSH keys, package registry tokens and git credential stores.
- Process environment. Secrets exported in the shell profile are inherited by the agent and by every command it runs, so a single
envorprintenvcall reveals them. - Command output. Running a deployment script, a database client or a debug command can print tokens into the conversation.
- Agent state files. Session history, chat logs and permission files that the tool writes to disk can capture secrets that appeared during a session.
Once a secret is in the model's context it can be repeated in a later answer, written into a file, sent to the model provider as part of the prompt, or passed to another tool. This is the agent form of OWASP LLM02:2025 Sensitive Information Disclosure and of Credentials In Files (T1552.001).
Leak path one: injected instructions and outbound requests
The Adversa AI research, published on 6 October 2026, is a clear example of an indirect prompt injection that ends in exfiltration. According to Adversa's write-up:
- The user asked Copilot CLI, running in autopilot mode without per-action confirmation, to fetch one attacker-controlled URL. No further interaction was needed.
- The page carried encrypted instructions. Decrypting them led the agent to read a local
.env.prodfile and then make an outbound HTTP request carrying the file's contents to an attacker endpoint. Adversa notes the target file pattern could cover other files the agent can read, including outside the working directory. - The chain took about 28 seconds. Adversa reports that the session transcript did not show the destination host or that file contents left the machine.
- Results depended on the model. One model completed the chain in 50% of runs while two others refused. With automatic model selection, the more permissive model could be assigned without the user choosing it.
- Adversa reported the issue to GitHub on 17 September 2026. GitHub validated it on 1 October 2026 but did not treat it as a vulnerability, because the user had asked the CLI to fetch the content while granting full autonomous permissions.
The pattern generalises to any terminal agent that can read files and make network requests in the same session. It maps to LLM Prompt Injection (AML.T0051) followed by Exfiltration via AI Agent Tool Invocation (AML.T0086). Defences that do not depend on the model refusing:
- Keep autonomy low in sessions that fetch untrusted content. Require confirmation for new network destinations and for writes outside the workspace, and show resolved arguments rather than templates.
- Process fetched content in a context with no tools and no credentials, and pass only structured results back to the session that can act.
- Restrict outbound network access from the agent's sandbox or container to the hosts the task needs.
- Pin the model in sensitive repositories rather than leaving model selection automatic.
Adversa also recommends detecting sequences rather than single payloads: untrusted content enters, code runs, local files are read, then the agent contacts an unrelated host.
Leak path two: saved approvals and agent configuration files
The second path needs no attacker at first. Agents save state to make work smoother, and some of that state is plain text in the project folder.
Claude Code documents that when you choose "Yes, and don't ask again" for a Bash command, it saves that approval as an allow rule in .claude/settings.local.json. The rule is the command as approved. If the command was mysql -p'secret' ... or included an API key in a header, the secret is now in a file. Claude Code adds **/.claude/settings.local.json to the global git excludes file the first time it writes the file, but a file created by hand, a repository that tracks it already, or a different packaging route (an npm package, a container image, a zip) can still carry it out.
As covered on our Claude Code settings leak breach page, Apiiro researchers found 1,379 distinct secrets in 1,122 public repositories that held this file, and 2,539 secrets in total once history, forks, shared settings files and chat logs were included. They included database passwords, SSH logins, source control and package tokens, and AWS keys. Many were in formats such as PGPASSWORD= or sshpass -p that common secret scanners missed.
The lesson applies to every tool: any file an agent writes can contain secrets that passed through the session. Treat agent configuration directories, session histories and logs as sensitive. Our Coding Agent Configuration File Attacks guide covers the reverse problem of malicious configuration arriving through a repository.
Leak path three: secrets in context and in commands
Even without an attacker or a saved file, secrets that enter the model's context travel further than developers expect:
- The prompt, including file contents and command output, is sent to the model provider. Check the data handling terms for each tool and plan.
- The agent may copy a key from a file into generated code, a test, a README or a commit message.
- Commands the agent writes may put passwords on the command line, where shell history, process listings and the saved approval file can capture them.
- Logs and transcripts kept for audit or debugging can hold the same values.
Our AI Coding Tools and Secrets Sprawl guide covers how AI coding tools spread secrets across repositories more broadly.
Tool settings that limit secret exposure
The three tools below are listed alphabetically. Each section describes that tool's own documented settings; apply whichever controls your chosen tool provides.
Claude Code
- Deny reads of secret files. Anthropic's settings documentation shows
"deny": ["Read(./.env)", "Read(./.env.*)"]underpermissionsto stop Claude Code reading.envfiles. Extend the list to credential files your projects use. - Use managed settings for policy. Managed settings, delivered by a
managed-settings.jsonfile, MDM or server-managed settings, sit at the top of the precedence order, so deny rules set there cannot be overridden locally. - Know where approvals go. Standing approvals are written to
.claude/settings.local.jsonat the repository root. Review that file, keep it out of commits, packages and images, and never approve a command that contains a literal secret. - Restrict scope. The
permissions.blockReadsOutsideWorkingDirectoriessetting limits reads to working directories. - Platform detail: Claude Code Security Guide.
Gemini CLI
- Enable the sandbox. Gemini CLI documents sandboxing through
--sandbox, theGEMINI_SANDBOXvariable or"sandbox": truein thetoolssection ofsettings.json, using macOS Seatbelt or a Docker or Podman container. - Choose a tighter profile. The default Seatbelt profile confines writes to the project directory but allows broad file reads and network access. Proxied, restrictive and strict profiles, selected with
SEATBELT_PROFILE, tighten this. The container sandbox limits file system access to the project directory. - Keep secrets out of mounts. Review
SANDBOX_MOUNTSand avoid mounting home directory credential folders into the sandbox. - Platform detail: Gemini CLI and Gemini Code Assist Security Guide.
GitHub Copilot CLI
- Launch from trusted directories only. GitHub advises launching Copilot CLI only from directories you trust and, typically, not from your home directory. It notes that scoping of permissions is heuristic and files outside trusted directories may not be fully protected.
- Use tool allow and deny flags.
--allow-toolapproves a specific tool,--deny-tooltakes precedence over--allow-all-toolsand--allow-tool. Reserve--allow-all-tools,/permissions allow-alland autopilot for isolated environments. - Isolate autonomous runs. GitHub recommends running Copilot CLI in a virtual machine, container or dedicated system with tightly controlled permissions when using automatic approval.
- Protect provider keys. When a custom model provider is used,
COPILOT_PROVIDER_API_KEYholds the key in the environment, so keep it out of shell profiles shared with other tools. - Platform detail: GitHub Copilot Security Guide.
Workstation hygiene that works across tools
Tool settings reduce what the agent may do. Workstation hygiene reduces what there is to find.
- Remove long-lived secrets from project folders. Replace
.envsecrets with references resolved at runtime from a secrets manager, or with short-lived credentials from single sign-on and workload identity. See the Cloud Secrets Managers Guide. - Keep secrets out of the shell profile. Do not export production tokens globally. Inject them per command through a secrets manager CLI, so the agent's inherited environment is clean.
- Never put secrets on command lines. Use credential files with restrictive permissions, client configuration or prompts for interactive passwords, so neither history nor approval files capture them.
- Separate development and production credentials. A developer workstation where an agent runs should not hold production database passwords at all.
- Run autonomous sessions in containers. Mount only the project, with no home directory and no credential folders, and restrict egress.
- Scan agent files before they leave. Add agent configuration directories, session histories and logs to pre-commit secret scanning and to packaging and image build checks. Write custom rules for password patterns such as
PGPASSWORD=,sshpass -pandmysql -p. See the Git Secret Scanning Guide.
Detection and response
Signals
- Agent sessions reading
.envfiles or home directory credential folders that the task did not need. - Outbound requests from agent processes to hosts not seen before, especially soon after fetching external content.
- Agent configuration files such as
.claude/settings.local.jsonappearing in commits, pull requests, npm packages or container layers. - Secret scanner hits in files under agent directories, or in commits co-authored by an AI tool.
- Cloud or database credentials used from new locations after a developer's agent session.
Response
- Rotate every secret the agent could read in the affected session, not only the one known to have leaked. Prioritise production and cloud credentials.
- Remove the file from the repository and its history, forks and published packages, and treat removal as clean-up, not containment: rotation is the containment.
- Review the session trace for the sequence of fetch, file read and outbound request to establish what left the machine.
- Lower the tool's autonomy settings and add deny rules for the paths involved before resuming.
Our How to audit AI coding assistant tokens and config files guide gives a step-by-step audit.
Common failure patterns
- Running terminal agents from the home directory, where every credential file is in reach.
- Using autopilot or allow-all modes in sessions that also fetch web content or read issues from outside contributors.
- Approving commands with literal passwords and choosing "don't ask again".
- Assuming the default git excludes cover every route out, while packages, images and archives ship the file.
- Exporting production tokens in the shell profile, so every agent and every command inherits them.
- Relying on generic secret scanners that miss password flags in command lines.
- Leaving model selection automatic in sensitive repositories, so the session's resistance to injection varies without notice.
- Deleting a leaked file without rotating the secret.
Practitioner checklist
- Inventory which AI command-line tools developers use and how they are configured.
- Deploy organisation-managed settings that deny reads of
.envand credential files where the tool supports it. - Require sandboxed or containerised runs for any autonomous or allow-all mode.
- Block agents from launching in home directories and restrict mounts to the project.
- Restrict egress from agent sandboxes and require confirmation for new network destinations.
- Add agent configuration folders and session logs to pre-commit, packaging and image secret scanning with custom password rules.
- Move developer secrets to a secrets manager or short-lived credentials and remove production secrets from workstations.
- Train developers never to approve standing rules for commands containing secrets.
- Prepare a rotation runbook for secrets exposed in an agent session.
Standards and references
- Adversa AI: Cryptographic Context Injection in GitHub Copilot CLI (6 October 2026)
- Anthropic: Claude Code settings files and precedence
- Google: Gemini CLI sandboxing documentation
- GitHub: About GitHub Copilot CLI
- OWASP: LLM01:2025 Prompt Injection
- OWASP: LLM02:2025 Sensitive Information Disclosure
- MITRE ATLAS: LLM Prompt Injection (AML.T0051)
- MITRE ATT&CK: Credentials In Files (T1552.001)
Related NHI Mgmt Group resources: Environment Variables and .env Files · AI Coding Tools and Secrets Sprawl · Coding Agent Configuration File Attacks · Git Secret Scanning Guide