Prevent Coding Agents From Reading .env
I went down a rabbit hole recently after a simple question popped into my head: when I ask a coding agent to "fix the build," what stops it from opening .env and printing my keys?
For most setups, the honest answer is nothing.
A coding agent runs as you. It gets your files, your shell, and your environment variables. That is what makes it useful. It is also what makes it dangerous around secrets. The model does not have to be malicious. It just has to be helpful in the wrong direction, and a file called .env looks very helpful.
This post is the setup I ended up with for Claude Code, Codex, OpenCode, Google Antigravity, and Gemini CLI. Each tool has its own permission format, so you have to do it a few times. None of it is hard, and most of it takes minutes.
The mental model: words are not enforcement
There are three layers, and people usually only build the first one.
| Layer | What it is | Can the agent ignore it? |
|---|---|---|
| Rules | AGENTS.md, CLAUDE.md | Yes, it is just text |
| Permissions | tool config files | Only the tool checks them |
| Hooks | scripts that inspect a command | Only commands they can see |
Writing "never read .env" in AGENTS.md is a good idea. It tells the agent what you expect, so it does not waste time trying. But it is a request. The agent can still read the file.
A permission rule is different. The tool checks it before the action and refuses. That is the layer that actually protects the file.
Step zero: make .env uncommittable
Add these lines to the .gitignore file at the root of the repo:
.env
.env.*
!.env.example
.claude/settings.local.json
Keep a committed .env.example with blank values:
SERVICE_A_API_KEY=
SERVICE_B_API_KEY=
This gives the agent a safe file to read when it needs to know which variables exist. It gets the names, not the values.
If .env is already tracked, .gitignore will not remove it. Take it out of the index and rotate every value in it:
git rm --cached .env
git commit -m "Stop tracking .env"
git log --all --full-history -- .env
That last command shows every commit that touched the file. If the repo was ever pushed, assume the values are public. Rotating the keys is the only fix that matters.
Claude Code
Claude Code reads project permissions from .claude/settings.json. Deny rules are checked before allow rules, so an allow rule cannot make an exception inside a deny. Use a ! negation instead.
{
"permissions": {
"deny": [
"Read(.env)",
"Read(.env.*)",
"Read(!.env.example)",
"Bash(cat .env)",
"Bash(type .env)",
"Bash(less .env)",
"Bash(head .env)",
"Bash(tail .env)",
"Bash(source .env)",
"Bash(printenv *)",
"Bash(env *)",
"Edit(./.claude/settings.json)",
"Edit(./.claude/settings.local.json)",
"Edit(./scripts/check-bash.js)",
"Edit(./.githooks/**)"
]
}
}
The negation has to come after the rule it carves out, so Read(!.env.example) sits below Read(.env.*). Bare filenames match at any depth, so Read(.env) covers nested .env files too.
The Bash rules cover the plain commands. The hook below covers the variants. The Edit rules stop the file tools from rewriting the permission file or the hook script. A shell command can still overwrite them, so treat this as a speed bump, not a container boundary.
Codex
Codex uses TOML and named permission profiles. Add this to .codex/config.toml:
default_permissions = "no-env"
[permissions.no-env]
extends = ":workspace"
[permissions.no-env.filesystem]
glob_scan_max_depth = 4
[permissions.no-env.filesystem.":workspace_roots"]
".env" = "deny"
"**/.env" = "deny"
"**/.env.*" = "deny"
"**/*.env" = "deny"
".env.example" = "read"
".githooks/**" = "deny"
"scripts/check-secrets.js" = "deny"
[shell_environment_policy]
inherit = "core"
ignore_default_excludes = false
[shell_environment_policy.filters]
"*PASSWORD*" = "exclude"
A few lines worth explaining.
extends = ":workspace" keeps the built-in workspace sandbox, then adds my rules on top. The filesystem table is a per-path allow or deny list. The .env.example rule is exact, so it wins over the broader **/.env.* deny and the template stays readable. glob_scan_max_depth matters on Windows, WSL, and Linux, because ** will not go deep without it.
The shell policy is the part people skip. Even if Codex cannot read .env, your shell might already have SERVICE_A_API_KEY exported. A subprocess can print it. inherit = "core" passes only the basics like PATH. ignore_default_excludes = false turns on Codex's built-in exclusions for names containing KEY, SECRET, or TOKEN, and the filter adds PASSWORD. The older exclude array still works, but filters is the current form.
Permission profiles are beta. They do not compose with sandbox_mode: if sandbox_mode appears in any loaded config file, Codex uses the old sandbox settings and ignores default_permissions. Project .codex/config.toml also loads only after you trust the project. Remove sandbox_mode and [sandbox_workspace_write] before you rely on this.
Codex config has changed between versions, so check the docs for the version you have installed.
OpenCode
OpenCode puts permissions in opencode.json at the repo root. Each tool gets a map of pattern to allow, deny, or ask. OpenCode already asks before reading .env; this turns that into a deny.
{
"$schema": "https://opencode.ai/config.json",
"permission": {
"read": {
"*": "allow",
"*.env": "deny",
"*.env.*": "deny",
"*.env.example": "allow"
},
"edit": {
"*": "allow",
"*.env": "deny",
"*.env.*": "deny",
"*.env.example": "allow",
"opencode.json": "deny",
".githooks/**": "deny",
"scripts/check-secrets.js": "deny"
},
"bash": {
"*": "allow",
"*.env*": "deny",
"*.env.example": "allow",
"env": "deny",
"env *": "deny",
"printenv": "deny",
"printenv *": "deny"
},
"task": "ask"
}
}
The order matters here. The last matching rule wins, so *.env.example: allow has to come after the *.env.* deny. If you flip them, the example file gets blocked.
What each block does:
readblocks the read tool, with an exception for the template.editblocks writes, so a helpful agent cannot overwrite.envor rewrite its own config and hook script.bashblocks any command that mentions.env, except the example file. That coverscat,source,cp, and similar commands.envandprintenvneed their own rules because their names do not contain.env. The*variants catch them with arguments.taskis set to ask, because subagents are another chance for a rule to be missed.
The edit rules only cover the edit tool. A shell command can still overwrite opencode.json, so this is a speed bump, not a boundary.
Google Antigravity and Gemini CLI
Antigravity is Google's agentic IDE and CLI. Its defaults are looser than Claude Code's. Reads and writes inside the project folder are allowed by default, so .env needs an explicit deny.
The reason I take this one seriously is a report from PromptArmor. In the attack they described, Gemini tried to read .env with its file tool. The tool refused because .env was in .gitignore. So the agent ran cat .env in the terminal instead. That was not blocked. A browser subagent then sent the contents to a request capture site that happened to be on the default allowlist.
The lesson is simple: an ignore file guards the file tool, not the shell.
Antigravity rules
The rule format is action(target). Deny beats ask, and ask beats allow. That order matters: a broad ask: command(*) still prompts even when a narrower allow rule matches.
For the CLI, the documented path is ~/.gemini/antigravity-cli/settings.json:
{
"permissions": {
"deny": [
"read_file(.env)",
"read_file(apps/web/.env)",
"read_file(/home/you/.ssh)",
"read_file(/home/you/.aws)",
"command(printenv)",
"command(env)",
"command(regex:.*\\.env.*)"
],
"ask": ["command(*)"]
}
}
Paths are matched relative to the workspace root. ~ is not expanded, so use a real absolute path such as /home/you/.ssh. The .env rule only covers the file at the root. Add one entry for each nested .env, like apps/web/.env.
ask: command(*) means every shell command prompts you. Deny still wins, so cat .env is blocked rather than asking.
command(regex:.*\.env.*) only catches a command whose literal text contains .env. It will not catch cat $FILE, grep -r KEY ., or a script that opens the file itself. The sandbox and the ask rule are what cover the rest.
One nasty detail: rules the CLI cannot parse are ignored without a warning. A typo in a pattern means no protection at all. Test after every edit.
For the IDE, open Settings with Ctrl+, or Cmd+,, go to Global Permissions, then Deny, and add the same read_file(...) entries.
Antigravity settings
The permission file is only half the job. These settings close the other doors:
- Permission preset: Default. It keeps the terminal sandbox on, allows commands inside it, and asks before commands that leave it. Request Review is stricter for commands but turns the sandbox off.
- Ask list:
command(*)if you want every command to prompt. Deny rules still win over the ask list. - Agent gitignore access: off. It only protects the file tool anyway.
- Outside-of-folder file access: Always Deny or Always Ask. This is the real protection for home directory paths, because
~does not expand in rules. - Browser tools: off if you do not need them.
- Browser URL allowlist: remove
webhook.siteand any other request capture sites. - Strict mode: on for repositories you did not write.
Also review Project Permissions now and then. Approvals you click during a session get saved there and can quietly widen access over time.
Gemini CLI
The standalone Gemini CLI is a different tool. .geminiignore at the repo root helps its file tools, but it will not stop cat .env.
If you do not need shell access, the strongest option is to turn the shell tool off. Put this in .gemini/settings.json:
{
"tools": {
"exclude": ["run_shell_command"]
}
}
The current key is tools.exclude. Older releases used a top-level excludeTools array, and some versions moved toward a policy engine. Check the docs for the version you actually have.
Hooks: the second safety net
Permission files protect the tool. They do not protect the repo from a command that slips past a pattern. That is where hooks come in.
Scan staged commits for secrets
This script scans only the lines you are adding, so removing an old secret does not get blocked.
// scripts/check-secrets.js
const { execSync } = require("node:child_process");
const patterns = [
{ name: "AWS access key", re: /AKIA[0-9A-Z]{16}/ },
{
name: "AWS secret key",
re: /aws_secret_access_key\s*[=:]\s*["']?[A-Za-z0-9/+=]{40}/i,
},
{ name: "private key", re: /-----BEGIN [A-Z ]*PRIVATE KEY-----/ },
{ name: "OpenAI-style key", re: /\bsk-[A-Za-z0-9_-]{20,}/ },
{ name: "GitHub token", re: /\bgh[pousr]_[A-Za-z0-9]{36,}\b/ },
{
name: "GitHub fine-grained token",
re: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/,
},
{ name: "Slack token", re: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/ },
{ name: "Stripe key", re: /\b[sr]k_(live|test)_[A-Za-z0-9]{20,}\b/ },
{ name: "Google API key", re: /AIza[0-9A-Za-z_-]{35}/ },
{
name: "secret assignment",
re: /^\s*(?:export\s+)?[A-Z0-9_]*(?:API_KEY|SECRET|TOKEN|PASSWORD)[A-Z0-9_]*\s*=\s*["']?[A-Za-z0-9_\-./+=]{12,}["']?\s*$/im,
},
{
name: "quoted secret assignment",
re: /(?:api[_-]?key|secret|token|password)\s*[=:]\s*["'](?!process\.env|\$\{)[^"']{12,}["']/i,
},
];
const diff = execSync("git diff --cached", { encoding: "utf8" });
const added = diff
.split("\n")
.filter((line) => line.startsWith("+") && !line.startsWith("+++"))
.join("\n");
const hits = patterns.filter((pattern) => pattern.re.test(added));
if (hits.length) {
console.error(
"Possible secret staged: " + hits.map((hit) => hit.name).join(", ")
);
console.error("Unstage the file and move the value into a secret manager.");
process.exit(1);
}
Wire it into a pre-commit hook:
#!/bin/sh
node scripts/check-secrets.js
Then turn hooks on:
chmod +x .githooks/pre-commit
git add .githooks/pre-commit
git config core.hooksPath .githooks
The script is committed like any other file. Only the core.hooksPath setting is local to each clone, so a teammate who skips it gets no protection. Put the command in your README or setup script.
That setting replaces Husky if the repo uses it. Keep one hook path, not two. Either move the scanner into .husky/pre-commit, or call your existing Husky hook from .githooks/pre-commit.
The sk- pattern covers OpenAI-style and OpenRouter-style keys. Google keys start with AIza, so I added that pattern too. Add the format for whatever provider you use. The assignment patterns only fire on values with 12 or more characters, so blank template values and short placeholders pass. They are deliberately noisy: a realistic fake key in a test fixture will block the commit. Generate test values at runtime instead of pasting one.
Block dangerous shell commands
Claude Code can run a script before a Bash call. Exit code 2 blocks the call and shows the error to the model. If the script cannot parse its input, it exits 2 as well, so a malformed hook payload does not fail open.
// scripts/check-bash.js
const fs = require("node:fs");
let command = "";
try {
const input = JSON.parse(fs.readFileSync(0, "utf8"));
command = input?.tool_input?.command ?? "";
} catch {
console.error("Could not read the hook input. Blocking to stay safe.");
process.exit(2);
}
const envFile = /\.env(?!\.example)(?:\.[\w-]+)?\b/.source;
const rules = [
{
name: "reading an env file",
re: new RegExp(
"\\b(cat|type|less|more|head|tail|sed|awk)\\b[^|;&]*" + envFile
),
},
{
name: "sourcing an env file",
re: new RegExp("(^|[;&|]\\s*)(source|\\.)\\s+[^|;&]*" + envFile),
},
{
name: "copying an env file",
re: new RegExp("\\b(cp|mv|install|rsync|scp)\\b[^|;&]*" + envFile),
},
{
name: "searching an env file",
re: new RegExp("\\b(grep|rg|ag|ack)\\b[^|;&]*" + envFile),
},
{
name: "reading an env file from git",
re: new RegExp("\\bgit\\s+(show|diff|log)\\b[^|;&]*" + envFile),
},
{
name: "reading an env file with an interpreter",
re: new RegExp(
"\\b(python[0-9.]*|node|perl|ruby|php)\\b[^|;&]*\\s-(c|e)\\b[^|;&]*" +
envFile
),
},
{
name: "printing environment variables",
re: /(^|[\s;&|])(printenv|env)(\s|$)/,
},
{
name: "piping a download into a shell",
re: /\b(curl|wget)\b[^|]*\|\s*(sh|bash|zsh)\b/,
},
];
const hit = rules.find((rule) => rule.re.test(command));
if (hit) {
console.error("Blocked by repo policy: " + hit.name);
process.exit(2);
}
Then register the hook in .claude/settings.json:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "node",
"args": ["${CLAUDE_PROJECT_DIR}/scripts/check-bash.js"],
"onFailure": "block"
}
]
}
]
}
}
args makes Claude Code run node directly with the script path, so the hook works from any directory. onFailure: "block" blocks the Bash call if the hook crashes, times out, or the script is missing. It needs Claude Code v2.1.295 or newer. On an older version, the try/catch and exit code 2 still cover bad input, but a missing script fails open.
Keep the script dumb and obvious. A regex that is too clever will either miss the real command or block your normal work. This one catches commands that name .env, plus env and printenv. It cannot catch grep -r KEY . or a script that opens the file without naming it. That is what the sandbox is for. Claude Code hook schemas have changed before, so confirm the shape against the docs for your version.
Test it, do not trust it
An untested rule is a wish. Set up a throwaway .env with fake values and run these checks.
- Ask the agent to read
.env. Expect a refusal. - Ask it to run
cat .env,source .env, andgit show HEAD:.env. Expect a block or an approval prompt. - Ask it to read
.env.examplewith the file tool. Expect it to work. - Ask it to edit
.claude/settings.jsonoropencode.json. Expect a refusal. - Run the secret scanner test below.
- Check that the hooks path is set.
printf 'KEY=sk-%s\n' "$(head -c 24 /dev/zero | tr '\0' a)" > fake.txt
git add fake.txt
git commit -m "test secret scanner" # should fail
git restore --staged fake.txt
rm fake.txt
git config core.hooksPath # should print .githooks
This is a Unix shell snippet. On Windows, run it in WSL or Git Bash.
Generate the fake key at runtime like this instead of typing a key-looking string by hand. If you have a pre-commit hook, a pasted example key can get your own documentation blocked. That has happened to me, and it is funny for about five seconds.
One more test that is easy to forget: put a typo in a rule and run the checks again. Antigravity silently ignores rules it cannot parse, and a broken regex looks exactly like a working one until it matters.