Skip to content

Your AI coding agent can read your .env: how to protect your keys

From the work/ 13 min read

Your AI coding agent reads .env without asking. Three measures: a Read deny rule, test keys in development and real keys only in your platform's secret manager.

  • AI
  • Security
  • Claude Code
In this article (9)
  1. Why your AI agent can read your .env
  2. Block reads with a deny rule
  3. Test keys in development
  4. Real keys in the platform's secret manager
  5. .gitignore is not enough
  6. If a key leaked: rotate it
  7. Common mistakes
  8. Frequently asked questions
  9. Checklist

An AI coding agent like Claude Code can read your .env without asking: reading project files needs no approval, and whatever it reads goes into the conversation. Protect it with three measures: a Read deny rule for your secret files, test keys in development, and real keys only in your platform's secret manager.

This article does not repeat what is already written: the full rule syntax lives in Claude Code permissions in settings.json, and blocking the file from the terminal in the hook that protects your .env. Here the three measures come together, along with why .gitignore does not protect you from the agent and what to do when a key has already leaked. Checked against the official docs on November 19, 2026.

Why your AI agent can read your .env

Per the Claude Code permissions docs, read-only tools, such as reading a file or searching with Grep, need no approval inside the working directory. Commands like cat, head and grep belong to a built-in read-only set that runs without a prompt in every mode. Your .env sits in the working directory, so to the agent reading it is as ordinary as reading package.json.

Auto mode does not stop it either. In the list of what its classifier allows by default, the permission modes docs include reading .env and sending the credentials to their matching API. That makes sense for day-to-day work; for your keys it means their values enter the conversation.

And what enters the conversation does not stay on your screen. The data usage page says Claude Code sends prompts and model outputs over the network, encrypted with TLS, and stores transcripts locally in plaintext under ~/.claude/projects/ for 30 days by default (adjustable with cleanupPeriodDays). From there a key can also end up in a test file the agent wrote, in a log or in a commit.

what the agent reads enters the conversation.envSECRET_KEY=…in your folderAI agentRead · cat · grepno approval neededconversationsent to the modelover TLSdenyReadfile, log or commitwhatever the agent writes~/.claude/projects/plaintext, 30 days by defaultdeny cuts the first arrowsource: Claude Code docs (permissions, data usage)

Scroll the figure sideways to see all of it

The agent does not even have to make a mistake. One instruction hidden in a README, an issue or a skill you installed is enough: the agent reads it as context and may follow it. That is why you should scan a skill before installing it, and why none of the three measures depends on the model behaving well.

Block reads with a deny rule

The first measure is a Read deny rule for your secret files. It goes in .claude/settings.json, the project file you commit, so it protects the whole team:

{
  "$schema": "https://json.schemastore.org/claude-code-settings.json",
  "permissions": {
    "deny": [
      "Read(.env)",
      "Read(.env.*)",
      "Read(!.env.example)",
      "Read(*.pem)"
    ]
  }
}
  1. $schema gives your editor the SchemaStore schema, which flags a malformed rule such as an unclosed parenthesis. It checks the shape, not what the rule blocks.
  2. permissions.deny is the list of tool uses Claude Code blocks. A deny wins in every mode and from any settings file.
  3. Read(.env): a bare filename follows .gitignore syntax and matches at any depth, so it blocks the root .env and apps/web/.env alike.
  4. Read(.env.*) covers .env.local, .env.production and any other variant.
  5. Read(!.env.example) starts with !: it is a carve-out that reopens the template. It works because it comes after the rule that blocks it, in the same file; a ! listed first carves nothing out. The agent needs the variable names, not their values.
  6. Read(*.pem) blocks PEM certificates and private keys, also at any depth.

What it covers, exactly, per the permissions docs and the permissions.deny reference: Claude's file tools (Read, and on a best-effort basis Grep and Glob), @ mentions, the context your IDE shares, the file commands Claude Code recognizes in Bash, such as cat, head, tail, sed and tee, and redirect targets such as < .env. A Read deny also blocks Edit and Write on the same path.

What it does not cover, again per the docs: a command that reads files without naming them, such as grep -r pattern ., or a Python or Node script that opens the file itself. The docs name Bash commands and say nothing about PowerShell's Get-Content; on Windows, the PreToolUse hook closes that gap. For OS-level blocking the docs point to the sandbox, which limits what shell commands and their child processes can read. It runs on macOS, Linux and WSL2; on native Windows, Claude Code runs commands unsandboxed. One more thing that trips people up: a .claudeignore file has no effect.

To cover every project on your machine, put absolute rules in ~/.claude/settings.json: Read(//**/.env) and Read(//**/.env.*). The carve-out does not work there: a ! only trims relative rules from the same file, so .env.example stays blocked everywhere and no project file can reopen it. Path syntax is covered in depth in the permissions article.

Test keys in development

The deny rule narrows what the agent sees, but it has documented gaps. The second measure makes those gaps matter less: no key on your machine should be able to move money or touch real data. If the agent reads a test key, the worst outcome is rotating a key with no customers behind it.

Most providers keep the two worlds apart. In Stripe, for example, each sandbox has its own keys, prefixed sk_test_, rk_test_ and pk_test_, while live mode keys start with sk_live_, rk_live_ and pk_live_; objects in one mode do not exist in the other. Stripe also offers restricted keys that carry only the permissions your code uses. A working rule: if a key in your .env says live or opens the production database, it should not be there. For the database, use a local copy or a read-only user, as in the read-only Postgres MCP setup.

Watch the platform you deploy to as well. Per its variables docs, Railway passes the linked environment's variables to your terminal through railway run and railway shell. If your folder is linked to the production environment and you start the agent inside railway shell, the real keys sit in the environment of every command it runs, and the deny rule never notices because there is no file to read. Link your machine to a development environment. For whatever does end up in the environment, setting CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 strips the credentials it recognizes, by name or value, from the commands, hooks and MCP servers Claude Code starts (GitHub tokens are kept).

three measures, each covering a gap in the others01Read deny rulesettings.jsonblocks Read and catgaps: grep -r, scriptsnarrows what it sees02test keyssk_test_… locallyno customers behindcheap to rotatelimits the damage03secret managerRailway (sealed)Secret Managernever on your diskkeeps real keys awaynone depends on the model obeyingif one fails, the other two still holdStripe's sk_test_ prefix as an example

Scroll the figure sideways to see all of it

Real keys in the platform's secret manager

The third measure: production keys live in one place, the secret manager of the platform that runs your app, and in no file. Your service receives them as environment variables at start-up; neither your disk nor your repo holds them. Two examples, described from each platform's docs:

  • Railway. Each service's variables are set in its Variables tab and reach the build and the deployment as environment variables; every change is staged until you review and deploy it. A sealed variable is provided to builds and deployments but is never visible in the UI, cannot be read through the API, and is not provided by railway run or railway variables. Sealing cannot be undone.
  • Google Cloud. For Cloud Run, Google recommends storing keys and passwords in Secret Manager and passing them as an environment variable or a mounted volume. Environment variables resolve when the instance starts, so Google recommends pinning a secret version instead of using latest. The service identity needs the roles/secretmanager.secretAccessor role.

With all three measures, every key has a home and you know what happens if it escapes:

KeyWhere it livesCan the agent see it?If it leaks
Variable names, no values.env.example, in the repoYes, on purposeNothing to rotate
Test key.env.local on your machine, out of gitBlocked by deny, except through the documented gapsYou rotate a key with no real data
Real production keyThe platform's secret managerNo: only the deployed service gets itUrgent rotation
Real key in a local .envYour disk and, if the agent read it, the transcriptYes, as soon as one barrier failsUrgent rotation; it should not exist
where each key lives and who sees itkeywhere it livescan the agent see it?.env.examplenames onlythe repoin gityeson purposetest keysk_test_….env.localyour machine, out of gitnot with denyexcept documented gapsreal keyproductionsecret managerRailway, Secret Managernoonly the deployed servicereal key in .envlocalyour disk and the transcript~/.claude/projects/yesas soon as a barrier failsthe real key never on your diskgaps: grep -r and scripts that open the file

Scroll the figure sideways to see all of it

.gitignore is not enough

.gitignore tells git which files to leave out of a commit. It is not a rule for the agent: in Claude Code, the respectGitignore setting only changes what the @ file picker shows, not what the Read tool can open. And in git it does not cover everything either: the gitignore docs say files already tracked by Git are not affected. We tested it in a throwaway repo with git 2.54 and a fake key: a first commit with .env inside, then .env added to .gitignore.

$ git check-ignore -v .env
$ git check-ignore -v --no-index .env
.gitignore:1:.env	.env
$ git ls-files .env
.env
$ git status --short
 M .env
$ git rm --cached .env
rm '.env'
$ git commit -qm "stop tracking .env"
$ git log --oneline --all -- .env
<hash> stop tracking .env
<hash> first commit
$ git show HEAD~2:.env
PAYMENTS_SECRET_KEY=sk_test_FALSO_123
  1. git check-ignore -v .env prints nothing: to git, a tracked file is not ignored, even if .gitignore lists it.
  2. With --no-index it does show the rule: the pattern exists, it just does not apply to this file.
  3. git ls-files confirms .env is still in the index.
  4. git status shows it as modified: the next git commit -a commits the new value.
  5. git rm --cached removes it from the index without deleting it from disk, and the commit records that.
  6. git log -- .env shows the file is still in two commits of the history.
  7. git show recovers the key from the first commit. Anyone with a copy of the repo can do the same.

That is why GitHub's guide to removing sensitive data makes revoking or rotating the secret the first step; rewriting history comes later and is sometimes not even needed. If you struggle to see what goes into each commit while the agent works, review the git workflow for AI agents.

If a key leaked: rotate it

A key the agent read sits in the local transcript and travelled in a request to the model. A key that reached a commit is in every clone. Neither can be "unread": you rotate it. The general steps, including the order for a key that moves money, are in NEXT_PUBLIC_ variables and secrets. Here is the part that changes when you use a secret manager, for Secret Manager and Cloud Run (version numbers are illustrative):

# 1. Add the new key as a new version, read from standard input
gcloud secrets versions add PAYMENTS_KEY --data-file=-

# 2. Point the service at that version; this deploys a new revision
gcloud run services update my-service \
  --update-secrets=PAYMENTS_SECRET_KEY=PAYMENTS_KEY:2

# 3. When the new revision serves traffic, disable the old version
gcloud secrets versions disable 1 --secret=PAYMENTS_KEY
  1. versions add creates version 2 of the secret. With --data-file=-, gcloud reads the value from standard input, so it never lands in a file.
  2. services update with --update-secrets moves the environment variable to version 2. Since the value resolves when an instance starts, this new revision is required; the previous revision keeps the old key.
  3. versions disable turns off version 1 in Secret Manager. versions enable turns it back on if something breaks.

The commands come from Google's docs (add a secret version and the Cloud Run page above), and we checked them against the local help of Google Cloud SDK 581.0.0; we did not run them against a project. Disabling the old version in Secret Manager does not invalidate the key: only the provider can do that. The full order:

  1. Create the new key at the provider. In Stripe, "rotate" revokes the key and creates a replacement; if you pick a future expiry, both keep working for up to 7 days. If the key leaked, expire it now.
  2. Store it in the secret manager: the commands above, or in Railway you edit the variable and deploy the staged change.
  3. Check the app works with the new key.
  4. Revoke the old key at the provider. This is the step that actually closes the leak.
  5. Review the provider's logs from the day the key could have left.
  6. Close the door it went out through: the deny rule, the real key out of your .env and out of any file or commit the agent wrote. The local transcript keeps it until it is cleaned up, which is why you rotate rather than just delete.

Common mistakes

  • Relying on .gitignore to stop the agent. It only affects git and the @ picker; the Read tool ignores it.
  • Putting the carve-out before the rule. Read(!.env.example) listed first carves nothing out.
  • Writing Write(.env) or Grep(.env) in deny. Path rules are only matched as Read and Edit; those block nothing.
  • Creating a .claudeignore. It has no effect; move its entries into Read deny rules.
  • Keeping live keys in .env "just for testing". That is exactly the key you do not want in a transcript.
  • Starting the agent inside railway shell linked to production. The keys sit in the environment, where the deny rule does not look.
  • Deleting the file or rewriting history instead of rotating. The key lives on in clones, transcripts and logs.
  • Assuming the sandbox on Windows. On native Windows commands run unsandboxed; you need WSL2.

Frequently asked questions

Does the deny rule stop the agent from running cat .env?

Yes. The docs say Read deny rules apply to the file commands Claude Code recognizes in Bash, such as cat, head, tail, sed and tee, and to redirects such as < .env. They do not apply to grep -r over the folder or to a script that opens the file itself.

Is a line in CLAUDE.md telling it not to read .env enough?

No. Per the memory docs, Claude treats CLAUDE.md as context, not enforced configuration. The permission modes docs put it plainly: for a hard guarantee, add a deny rule.

Can the agent use my keys without reading the file?

Yes, if they are in the environment of the terminal you started it from: exported, or loaded by railway run or railway shell. The deny rule does not apply there. Keep test keys locally and set CLAUDE_CODE_SUBPROCESS_ENV_SCRUB=1 to strip them from the commands' environment.

Do I have to rotate a test key the agent read?

It is worth doing, and cheap: there are no customers behind it, so you rotate it without hurry or risk. That is the point of keeping only test keys on your machine. If it was a real key, rotation is urgent.

Checklist

  • .claude/settings.json has Read(.env), Read(.env.*) and the .env.example carve-out, in that order.
  • ~/.claude/settings.json blocks //**/.env if you want every project covered.
  • On Windows, the PreToolUse hook covers PowerShell.
  • The local .env holds only test or read-only keys.
  • Your folder is linked to a development environment, not production.
  • Real keys live in the secret manager, sealed or pinned to a version.
  • git ls-files lists no .env, and git log --all -- .env is empty.
  • You know how to rotate each key and where to read its logs.

Deny rules are one part of the permissions setup. For the rest, such as allow and ask, see Claude Code permissions in settings.json.

Saw this on Instagram? Every Reel guide is at ecomlabs.dev/guides.

Written by

Luis Morales

Luis Morales

Frontend and Shopify developer, EcomLabs

@luismoralesdev on Instagram

Published November 19, 2026 · updated November 20, 2026

← Blog