Skip to content

Keep API keys away from Claude Code: .env deny rules

How to stop Claude Code reading your .env file: Read deny rules, what they miss, the Bash sandbox, and setups where real keys never sit in the repo.

Keysquid team7 min read
On this page
  1. Why this matters
  2. Layer 1: Read deny rules
  3. The rules to add
  4. Path prefixes trip people up
  5. Which settings file
  6. What Read deny rules don't cover
  7. Layer 2: the Bash sandbox
  8. Why you need both layers
  9. Layer 3: keep production keys out of the folder
  10. A setup you can copy
  11. FAQ

To keep Claude Code out of your .env file, add Read deny rules such as Read(./.env) and Read(./.env.*) to .claude/settings.json, and turn on the Bash sandbox so scripts and shell commands can't read the file either. The two cover different gaps, and neither covers everything. The only setup with no gap is one where real production keys never sit in the folder the agent works in. This guide walks through all three layers, with the exact settings and the edge cases the documentation itself warns about.

Why this matters

A coding agent reads files to understand your project, and a .env at the repository root looks like configuration it should understand. Once a key's value has been read, it is in the conversation: it can end up in a summary, a generated test, a log line or a commit. The Register reported in January 2026 that Claude Code read a .env file even though it was listed in a .claudeignore file, and that a correctly written deny rule in settings.json did block it (The Register). That report was about an older version, but the lesson holds: rely on mechanisms the tool enforces, not on files the model is merely asked to respect.

Claude Code's documentation is clear on this point: "Permission rules are enforced by Claude Code, not by the model" (permissions). A note in CLAUDE.md saying "never read .env" is a request; a deny rule is a control.

Layer 1: Read deny rules

The rules to add

Add a permissions.deny list to a settings file. A good starting set for a typical project:

{
  "permissions": {
    "deny": [
      "Read(./.env)",
      "Read(./.env.*)",
      "Read(./secrets/**)",
      "Read(**/*.pem)",
      "Read(**/*.key)"
    ]
  }
}

The first two lines are the example Anthropic uses in its settings documentation (settings). A few details from the permissions docs are worth knowing:

  • One rule covers reading and writing. "A Read deny rule also blocks the Edit and Write tools on the same path, including creating a new file there" (permissions).
  • Patterns follow gitignore conventions, so a bare file name matches at any depth, and Read(secrets/**) in a deny rule matches a secrets directory anywhere under the working directory.
  • You can carve out exceptions with a leading !, for example Read(*.env) followed by Read(!sample.env) so the agent can still read the example file. A carve-out can't reopen a file inside a directory that a rule blocks as a whole.
  • Write and Glob rules never match. The docs list Write(path), NotebookEdit(path) and Glob(path) as patterns that never match; use Edit(...) and Read(...) instead.

Path prefixes trip people up

The leading characters of a path change its meaning (permissions):

PatternMeans
./path or pathRelative to the current directory
/pathRelative to the settings file's location, not the filesystem root
//pathAbsolute path from the filesystem root
~/pathRelative to your home directory

The single slash is the trap. In project settings, /secrets/** anchors at the project root. In user settings (~/.claude/settings.json), it anchors at ~/.claude/, which is almost certainly not what you meant. For an absolute path, use two slashes: Read(//Users/alice/secrets/**). To block every .env file on the machine from your user settings, Read(//**/.env) does it.

Which settings file

FileApplies toUse it for
~/.claude/settings.jsonYou, every projectA personal safety net for .env, ~/.aws, ~/.ssh
.claude/settings.jsonEveryone in the repo (commit it)The project's secret paths
.claude/settings.local.jsonYou, this projectPersonal overrides
Managed settingsYour organisationRules nobody can loosen

When the same list appears in several files, Claude Code combines them rather than picking one (settings), and rules are evaluated "deny, then ask, then allow". An allow rule can't carve an exception out of a deny rule, so a teammate's local allow can't reopen your .env. Deny rules in a project file also apply immediately, before anyone has marked the folder as trusted.

Settings files are strict JSON: a comment or a trailing comma is a syntax error, so validate the file after editing it.

If you still have a .claudeignore file from older advice, the docs are blunt: "it has no effect, so move its entries into Read deny rules" (permissions).

What Read deny rules don't cover

This is the part most guides leave out. The documentation states that Read and Edit deny rules apply to Claude's built-in file tools, to file commands it recognises in Bash (cat, head, tail, sed, tee) and to the targets of redirections such as < file. Then it lists what they miss: "a command that reads files without naming them, such as grep -r pattern . run from the directory that holds the file, or ... arbitrary subprocesses that read or write files indirectly, like a Python or Node script that opens files itself" (permissions).

In practice that second gap is wide. Your test runner, your dev server and any library that calls dotenv will open .env happily, and their output, including a stack trace that prints a config object, comes straight back into the conversation. Bash deny rules such as Bash(cat *) don't close it either: the docs warn that a Bash rule "isn't a security boundary around the program", because the same program can be invoked in another form.

Layer 2: the Bash sandbox

For the subprocess gap, Claude Code has an operating-system sandbox. It is "a boundary that the operating system enforces around the shell commands Claude runs on your machine", covering those commands and the processes they start (sandboxing). It runs on macOS, Linux and WSL2 (Linux and WSL2 need bubblewrap and socat installed); on native Windows, commands run unsandboxed.

It is off by default. Turn it on with the /sandbox command, or in settings:

{
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "filesystem": {
      "denyRead": ["~/**/.env"]
    },
    "credentials": {
      "files": [
        { "path": "~/.aws/credentials", "mode": "deny" },
        { "path": "~/.ssh", "mode": "deny" }
      ],
      "envVars": [{ "name": "GITHUB_TOKEN", "mode": "deny" }]
    }
  }
}

The ~/**/.env entry comes from the sandboxing docs and blocks every .env file under your home directory for every sandboxed command. If you keep variants such as .env.production, check the "Sandbox path prefixes" section of the settings reference for how relative paths and wildcards resolve before adding them.

Three things to know before you rely on it:

  • Reads are open by default. Out of the box the sandbox lets commands read most of the machine, including credential files such as ~/.ssh and ~/.aws/credentials. You opt paths out with filesystem.denyRead and the credentials settings. The docs' own example of a tight setup denies the whole home directory and allows only the project: "denyRead": ["~/"], "allowRead": ["."].
  • It falls back silently unless you say otherwise. If a dependency is missing, Claude Code runs commands without the sandbox by default. failIfUnavailable: true makes it stop instead.
  • Its paths use a different convention. In sandbox settings, /tmp/build is absolute and ~/.kube is relative to your home directory, unlike permission rules where // means absolute. Don't copy patterns between the two blocks without checking.

The sandbox also starts with no network destinations allowed, so a script that did read a key can't simply post it somewhere. That's a useful second line, and a reason to keep network.allowedDomains short.

Why you need both layers

The sandbox has the mirror-image gap of deny rules: "The sandbox covers shell commands only. Claude's file tools, MCP servers, and hooks run outside it", and "A denyRead entry doesn't stop the Read tool" (sandboxing).

Path to your .envRead deny ruleSandbox denyRead
Claude's Read toolBlockedNot covered
cat .envBlockedBlocked
grep -r KEY .Not coveredBlocked
npm test loading dotenvNot coveredBlocked
An MCP server reading the fileNot coveredNot covered

Deny rules plus the sandbox close every row but the last. MCP servers run with your permissions, so only install ones you trust, and check what each tool returns.

Layer 3: keep production keys out of the folder

Both layers reduce what the agent can read. A better question is why a production key is in the working directory at all. The setups below remove the value instead of guarding it.

Use test keys locally. Most providers offer sandbox or test-mode keys (Stripe's sk_test_ and rk_test_, for example). If the only key in your local .env can't touch real money or real data, a leak into a conversation is a non-event. Keep live keys in your hosting platform and CI, not on laptops.

Inject at runtime instead of storing in a file. A secret manager's CLI can start your app with secrets as environment variables, so no .env exists on disk. Keysquid's CLI does this with keysquid run --project backend --env dev -- npm start (CLI docs), and most secret managers have an equivalent. Be honest about the limit: the started process holds the values, so if the agent runs it and the program prints its environment, the value still reaches the conversation. Combine it with dev-only keys.

Give the agent tools that never return values. This is the setup we built our MCP server for. The agent can list keys, see where each is used, move a .env into Keysquid with import_env, and request rotations, but no tool returns a secret value. When the agent needs to run tests with secrets, the opt-in run_with_secrets tool redacts every value, including encoded forms, from the output before the AI sees it; it is off by default and limited to an allowlist of programs. When the agent needs to call an API, Agent Vault adds the real key on the way out so the agent never holds it. Values move only between your machine and an agent you run, which is described in the security model.

Rotate anything that was exposed. If an agent session did read a production key, treat it as you would any other exposure: the value has been in a transcript you don't fully control. Our guide to the first 10 minutes after a leaked API key covers the order of operations.

A setup you can copy

For most projects, this combination is a sensible default:

  1. Commit .claude/settings.json with Read deny rules for .env, .env.*, key files and any secrets directory.
  2. Add Read(//**/.env) and deny rules for ~/.aws and ~/.ssh to your user settings, so every project starts protected.
  3. Enable the sandbox with failIfUnavailable: true, a denyRead entry such as ~/**/.env, and a short network allowlist.
  4. Keep only test or development keys on your machine; inject them at runtime where you can.
  5. Give agents tools that use keys without returning them, and rotate any key that ever appeared in a session.

None of these steps is hard. The mistake is stopping at the first one and assuming the file is now invisible.

Frequently asked questions

Does .claudeignore stop Claude Code from reading .env?

No. Claude Code's permissions documentation says a .claudeignore file has no effect and that its entries should be moved into Read deny rules in a settings file.

Does a Read deny rule stop Claude from running cat .env?

Yes for commands Claude Code recognises as file commands, such as cat, head, tail, sed and tee, and for shell redirections. No for commands that read files without naming them, such as grep -r from the parent directory, or for scripts that open the file themselves. For those you need the sandbox.

Is the Claude Code sandbox enough on its own?

No. The sandbox covers shell commands and the processes they start. Claude's built-in file tools, MCP servers and hooks run outside it, and the docs say a sandbox denyRead entry doesn't stop the Read tool. Use deny rules and the sandbox together.

Where should I put the deny rules?

In the project's .claude/settings.json if the whole team should get them, committed to the repo, or in ~/.claude/settings.json to cover every project you open. Deny rules from any level apply, and an allow rule can't override a deny rule.

What is the safest setup?

Keep production keys out of the working directory entirely. Use sandbox or test keys locally, inject real values at runtime from a secret manager, and give the agent tools that use keys without returning their values.

Sources

  1. code.claude.com/docs/en/permissions
  2. code.claude.com/docs/en/settings
  3. code.claude.com/docs/en/sandboxing
  4. www.theregister.com/2026/01/28/claude_code_ai_secrets_files/

For AI agents: this article is also available as Markdown.

Keep API keys away from Claude Code: .env deny rules · Keysquid