Skip to content
Agentic Control Plane
Incident series · Part 5 of 9
Stop Your Agent From… →

AI coding agents leaking .env secrets: stop it in 3 steps

David Crowe David Crowe · · Updated · 9 min read
governance defense-in-depth secrets-management pii-redaction
Share X HN LinkedIn

Run agents? ACP lets you see, control, and price every tool call they make — allow/ask/deny policy, per-session cost, and a full audit log for Claude Code, Cursor, Codex, and OpenClaw, in one command:

macOS · Linux · WSL
curl -sf https://agenticcontrolplane.com/install.sh | bash
Windows · PowerShell
irm https://agenticcontrolplane.com/install.ps1 | iex

Getting started →  ·  see your first governed call →  ·  free up to 5 agents

AI coding agents read .env files by default, and the keys inside end up quoted in commits, chat logs and tool output. Three steps stop most of it: block the read in unattended runs, mask key patterns in tool output, and log every read of a secret path.

GitGuardian counted 29 million new secrets exposed in public GitHub commits in 2025, up 34% on the year before. The same report found that commits co-authored by Claude Code leaked secrets at roughly double the baseline rate. The pattern is simple: the agent reads .env, treats the contents as text like any other, and pastes that text into a commit, a chat thread or a tool result.

The agent is not malicious. It is autocompleting. To the model, the value of STRIPE_SECRET_KEY is a string to reference like any other. It cannot tell that printing the string into a tool result makes it searchable forever.

Why this is the default failure

Agents read your environment for good reasons: checking that a key is present, looking up an endpoint, debugging config. The natural next step is “and here is what I found.” That is where the leak happens:

  • Asked to debug a Stripe webhook, the agent opens .env and quotes the secret in its explanation.
  • Asked to add a logging line, it reads existing config and includes the key in the diff.
  • Asked why a feature flag isn’t loading, it prints process.env, and the secrets sit in your chat history.
  • It commits its work, and the commit carries a log or quoted block with the secret in it.

Once a secret is in a commit, a chat log, a saved tool output or a CI artifact, it is leaked. Rotation is the only fix, and every service that depends on the key has to be updated.

Three steps that put a check between your agent and your secrets

Step 1: install the hook

For Claude Code, Cursor, Codex CLI and the other harnesses the installer detects:

curl -sf https://agenticcontrolplane.com/install.sh | bash

The hook checks each tool call (Read, Write, Edit, Bash, MCP) before it runs. ACP names file operations by path, so .env, .env.production and .env.local all land on the key Read.env, and credentials, credentials.json, *.pem and *.key land on Read.credentials. Shell reads are keyed by the command, so cat .env is Bash.cat. Your rules do not have to list every file name.

A new workspace starts in audit mode: everything is recorded, the safety floor applies, and your rules do not block yet. Run /acp-enforce (or flip the switch on the Policies page) when you are ready for step 2 to bite.

Step 2: deny secret reads in unattended tiers

On the Policies page at cloud.agenticcontrolplane.com, set the tool rules per tier. The same rules in policy JSON:

{
  "tools": {
    "Read.env":         { "background": { "permission": "deny" }, "interactive": { "permission": "ask" } },
    "Read.credentials": { "background": { "permission": "deny" }, "interactive": { "permission": "deny" } },
    "Write.env":        { "background": { "permission": "deny" }, "interactive": { "permission": "deny" } },
    "Bash.curl":        { "background": { "permission": "ask" } }
  }
}

What this means. In the background tier (scheduled jobs, headless agents, CI) the agent cannot read .env at all. In an interactive session the read is held: the call is blocked, you approve it on the Approvals page or from the approval email, then the agent retries. Only safety-floor holds show up as a prompt inside the session, and only in Claude Code. Codex has no ask prompt of its own, so there an ask is always a block. An unanswered request expires and counts as denied.

If ACP is unreachable, the Claude Code plugin keeps unattended tiers blocked and lets interactive sessions continue with an UNGOVERNED notice. The shared hook that Cursor, Codex and the other hook-file harnesses use fails open unless you set echo closed > ~/.acp/failmode on that machine. For an unattended runner, set it.

If the agent’s job really needs config (checking which environment a deploy targets, say), give that one read its own key and allow it. The point is to make “reading config to validate a deploy” and “reading all of .env to summarise it” two different rules, decided by you and not inside the model.

Step 3: turn on output redaction

Even when a read is allowed, the value should not reach the model. ACP scans tool output after the call. Its built-in detectors cover six PII types (email, credit card, SSN, IBAN, IP address, phone). Credential shapes such as Stripe keys, AWS access keys, GitHub tokens, PEM blocks and OpenAI or Anthropic keys are not in that set. Add them on the Patterns tab of the Policies page as custom regex patterns; matches are then masked, keeping the first and last two characters and starring the rest.

Output scanning starts in audit, which records what it would have redacted. Set it to redact for the tools that read secrets:

{
  "tools": {
    "Read.env": {
      "interactive": { "permission": "ask", "postTransform": "redact" }
    },
    "Bash.cat": {
      "interactive": { "permission": "allow", "postTransform": "redact" }
    }
  }
}

Now when the agent is allowed to read a sensitive file, what it receives for sk_live_abc… is sk****…** and the key name. The agent still knows there is a Stripe key on that line. It does not know the value, so whatever it quotes into a commit or a chat is the mask.

One limit matters here. The rewrite only works on harnesses that let a post-call hook replace the result. Claude Code does. Cursor and Codex do not: there the scan records the match in your activity log but the model still sees the value. The coverage table has the column per harness. On those harnesses, step 2 is the control that counts.

Free fourth step: read the log

Every read or write of a secret-class path is a row in your activity log, with the key (Read.env), the session, and whether the output was redacted. Credentials in a recognised format are redacted before a preview is stored. Filter on the key once a week and you will see which agent, and which task, keeps reaching for .env.

Frequently asked questions

How do I prevent Codex from reading .env?

Codex’s sandbox won’t do it alone. OpenAI’s docs say Codex can read files in both read-only and workspace-write modes, and its protected paths (.git, .agents, .codex, .aws) are write protections, not read blocks. Add a PreToolUse hook matched on Bash, which covers Codex’s shell commands, that denies any command naming .env; our Codex hooks examples show the shape. A pattern match is a tripwire, not a parser. Codex also cannot show a hook’s ask as a prompt, so with ACP an ask on Codex is a block you approve on the console.

Which service does an API key prefix like pplx- or xai- belong to?

The API key prefixes reference maps common prefixes found in .env files to the service that issued them, and covers how to keep a coding agent from reading or echoing them.

ai coding tools env file exposure: why do agents read .env at all?

For ordinary reasons: checking that a key is set, finding an endpoint, debugging config. The leak comes after, when the agent quotes what it read into an explanation, a diff, a printed process.env or a commit. Once a secret lands in a commit, chat log or CI artifact, rotation is the only fix.

Time to set up

  • One curl command (step 1): about 30 seconds.
  • Four tool rules on the Policies page (step 2): about 90 seconds.
  • Output redaction (step 3): one field per tool, plus the patterns you add.

A few minutes, and no agent in this workspace can read .env in a background run, and on Claude Code the values are masked before the model reads them. Compare that with rotating a leaked key across every service that uses it.

What an agent can read is half the leak; what it can send is the other half. The Tool Surface Index lists each declared tool by blast radius (read, write, send, publish), and getting started covers the install.

AgenticControlPlane.com

Share X HN LinkedIn
Get the next data drop
What agents actually cost, new tool-surface captures, and the occasional incident post-mortem — sent when we publish something worth your inbox, not on a schedule. Unsubscribe anytime.
Share: Twitter LinkedIn
More in Stop Your Agent From…
  1. 1. Stop your AI agent from running `rm -rf` on your files
  2. 2. Stop your AI agent from deleting your production database
  3. 3. Stop your AI agent from deleting files outside your project
  4. 4. Stop Your AI Agent From Force-Pushing and Rewriting Git History
  5. 5. AI coding agents leaking .env secrets: stop it in 3 steps · you are here
  6. 6. Stop your AI agent from leaking PII through tool calls
  7. 7. Stop your AI agent from burning through your API budget
  8. 10. Stop an AI agent from escalating IAM permissions on AWS, GCP and Azure
  9. 12. Make Your AI Coding Agent Ask Before It Runs Commands Over ssh
Related posts

← back to blog