Stop AI coding agents from reading .env files and secrets

An agent that can run shell commands can usually read any file the developer can. Ignore files do not change that. Here is what actually keeps Claude Code, Codex, Cursor and Copilot away from your keys, and where each control stops.

Next step

AI Agent Blocklist: block the coding agents that do not honour your secret rules, by package, process, app ID and domain

Deny rules only work in agents you manage. Our list covers the rest, with a risk grade on every entry and daily updates.

From $99 a month for one organisation See plans Ask a question

Three ways an agent reaches a secret

Most guides only cover the first path. A real block has to cover all three, or the agent simply takes another route when a rule stops it.

PATH 1

The agent's file tools

The built-in read, search and edit tools. Deny rules in the agent's settings cover this path well.

PATH 2

Shell commands

A command such as cat or grep run in the terminal. Agents recognise some file commands; others slip through rules that match command text.

PATH 3

Scripts and subprocesses

A Python or Node script, a test runner or a build tool that opens files itself. Only an operating system sandbox stops this path.

Environment variables are a fourth path. Anything exported in the developer's shell is inherited by the commands the agent runs, with no file read at all.

Where secrets hide on a developer machine

Before you write rules, list what you are protecting. These are the usual places, and each belongs in your deny lists.

.env, .env.*App keys, database URLs, API tokens
~/.sshSSH private keys and known hosts
~/.aws/credentialsCloud access keys
~/.config/gcloudCloud CLI sign-in data
~/.kube/configCluster credentials
.npmrc, .pypircPackage publishing tokens
secrets/, *.pem, *.keyCertificates and private keys
Shell profiles and historyExported tokens, pasted commands
Publishing and access tokens matter more than they look. In 2025 a tampered package release collected credentials from developer machines and posted them to repositories under the developers' own accounts. See AI coding agent security risks.

How to prevent Claude Code from reading .env and certain files

Claude Code has two layers: permission rules for its own tools and recognised commands, and a sandbox for everything else. Use both.

Claude Code
  1. Write Read deny rules. Patterns follow gitignore syntax. A bare name such as Read(.env) matches at any depth under the working folder.
  2. Anchor them correctly. // means the filesystem root, ~/ the home folder, ./ or no prefix the current folder. A single / anchors at the settings file's own location.
  3. Deliver them as managed settings and set allowManagedPermissionRulesOnly so project files cannot add their own allow rules.
  4. Turn on the sandbox and add the same paths to sandbox.filesystem.denyRead, so scripts and subprocesses are covered too.
  5. Strip credentials with the sandbox credentials settings for files and environment variables.
Know the limits: Read deny rules cover Claude's file tools, file commands it recognises such as cat, head and tail, and redirections. They do not cover a script that opens files itself. A .claudeignore file has no effect at all.
{
  "permissions": {
    "deny": [
      "Read(.env)",
      "Read(.env.*)",
      "Read(./secrets/**)",
      "Read(~/.ssh/**)",
      "Read(~/.aws/**)"
    ]
  },
  "allowManagedPermissionRulesOnly": true,
  "sandbox": {
    "enabled": true,
    "failIfUnavailable": true,
    "allowUnsandboxedCommands": false,
    "filesystem": {
      "denyRead": ["~/**/.env"]
    },
    "credentials": {
      "files": [
        { "path": "~/.ssh", "mode": "deny" }
      ]
    }
  }
}
The sandbox uses Seatbelt on macOS and bubblewrap on Linux and WSL2. Native Windows sessions are not sandboxed, so Windows developers who need it should run Claude Code in WSL2. Full deployment steps are in how to block or lock down Claude Code.

How to prevent Codex from reading .env and certain files

Codex enforces file rules through its sandbox. Admins set them as requirements that users cannot weaken; developers can add their own in a permission profile.

Codex CLI, IDE extension and app
  1. Admins: use requirements.toml. Under [permissions.filesystem], list deny_read paths. Absolute paths and ~ paths are allowed; paths starting with ./ are not.
  2. Place or deliver it: /etc/codex/requirements.toml on macOS and Linux, %ProgramData%\OpenAI\Codex\requirements.toml on Windows, macOS MDM, or cloud-managed requirements for ChatGPT business workspaces.
  3. Developers: use a permission profile. Add a deny entry for **/*.env under the profile's workspace roots.
  4. Trim environment variables with Codex's shell environment policy, so tokens in the shell do not reach the commands Codex runs. Check the current configuration reference for the keys.
Know the limits: on Linux, WSL and Windows, matching files are listed when each sandboxed process starts, so a file created later stays readable to that process. Profiles govern sandboxed commands; connectors, MCP servers, browser and computer use have their own controls.
# requirements.toml, set by admins
[permissions.filesystem]
deny_read = [
  "/**/*.env",
  "~/.ssh",
  "~/.aws",
]

# a developer's own profile in config.toml
[permissions.project-edit.filesystem.":workspace_roots"]
"**/*.env" = "deny"
Permission profiles are labelled beta by OpenAI and may change. For the full requirements file, including approvals and MCP, see how to block or disable Codex CLI.

Cursor and GitHub Copilot: what their ignore and exclusion features do

Both offer a way to hide files from AI features. Both vendors say clearly that it is not a security boundary, which means you need other controls around it.

FeatureWhat it doesWhat the vendor says it does not doWhat to add
.cursorignore in CursorKeeps listed files out of Cursor's AI features and indexingCursor calls it a convenience, not a security boundary; terminal commands and MCP tools can still read ignored filesApproval for terminal commands, MCP allowlist, secrets out of the workspace
Content exclusion in GitHub CopilotStops excluded files being used for suggestions and chat, on Business and Enterprise plansGitHub says it is not a filesystem security boundary, may miss indirect access by agents, is not guaranteed with third-party MCP servers and does not apply to symlinksOperating system permissions, agent mode limits, MCP registry
Admin settings for both are covered on block Cursor and disable GitHub Copilot.

Side by side: which control covers which path

Use this table to see where each agent is protected and where you still depend on keeping secrets out of reach. Only the last row covers every path on its own.

ControlFile toolsShell commandsScripts and subprocessesAdmin can enforce
Claude Code Read deny rulesYesRecognised file commandsNoYes, managed settings
Claude Code sandbox denyReadOwn rules applyYesYes, macOS, Linux, WSL2Yes
Codex deny_readNot stated by OpenAIYes, sandboxedYes, sandboxedYes, requirements.toml
.cursorignoreAI featuresNoNoNot as a boundary
Copilot content exclusionSuggestions and chatNot guaranteedNoYes, organisation settings
Secrets kept out of the workspaceYesYesYesThrough process and tooling

Environment variables: the secret path nobody checks

Many teams move secrets out of .env files and into the shell, then forget that the agent starts from that shell. Every command it runs inherits the variables.

DO

Load per command

Inject a credential only into the one command that needs it, from your secret manager, and let it expire.

DO

Use the agent's filter

Claude Code's sandbox can unset listed variables, and Codex has a shell environment policy for the same job.

AVOID

Tokens in profiles

Long-lived tokens exported in shell profiles are visible to every process the developer starts, agents included.

Mistakes that leave secrets readable

These come up again and again when teams review their agent settings. Each one looks like a working control until someone tests it.

MistakeWhy it failsFix
Relying on an ignore fileIgnore files steer AI features; they do not stop shell commands or scriptsDeny rules plus a sandbox, and secrets out of the folder
Rules only in a project fileProject files are written by whoever controls the repositoryPut deny rules in managed settings or admin requirements
Rules with the wrong anchorIn Claude Code, a single leading slash anchors at the settings file, not the filesystem rootUse // for absolute paths and ~/ for the home folder
Relative paths in Codex requirementsPaths that start with ./ are not allowed in deny_readUse absolute patterns such as /**/*.env, or ~ paths
Sandbox on, but not availableNative Windows sessions of Claude Code are not sandboxedUse WSL2, and set the sandbox to fail when it cannot run
Developers with local admin rightsLocal admins can edit managed files on their own machineLet MDM redeploy the files and limit admin rights where you can

If an agent may have read a secret

Treat it as exposed. Agent sessions send context to a model provider, and you cannot recall what was sent. Work through these steps the same day.

STEP 1

Rotate

Revoke and reissue the credential. Start with cloud keys, publishing tokens and database passwords, which attackers use fastest.

STEP 2

Check use

Look at the provider's access logs for sign-ins or calls from unfamiliar places since the session started.

STEP 3

Close the path

Add the missing deny rule or sandbox path, rerun the four tests, and record the change so the next review sees it.

If the agent was not one you approved, find out how it got there. Our page on shadow AI agents covers discovery, and the AI agent risk assessment helps you decide what to allow next. MCP servers deserve the same review; see MCP security risks.

Test your rules before you trust them

Put a dummy .env file with a fake value in a test repository, then ask the agent to use it in four different ways. Every test should fail.

  1. Direct readAsk the agent to open the .env file and show its contents.
  2. Shell readAsk it to print the file from the terminal with a common command.
  3. Script readAsk it to write and run a short script that opens the file.
  4. Variable readExport a fake token in the shell and ask the agent to print the environment.
If test 3 or 4 succeeds, your rules cover the tools but not the machine. Turn on the sandbox, strip the variables, or move the secret out of the workspace.

Who owns which part

Secret protection for agents fails when everyone assumes someone else set it up. Give each part a named owner.

TeamOwnsReviews
SecurityThe list of protected paths and variables, and which agents are approvedEvery quarter, and after each incident
Endpoint or platform teamManaged settings, requirements files and MDM delivery to every machineOn each agent release that changes settings
Engineering leadsKeeping secrets out of repositories and moving teams to run-time credentialsIn code review and onboarding
DevelopersReporting any agent that reads what it should not, and not working around the rulesEvery day, as part of normal work

The gap rules cannot close: agents you do not manage

Every control above lives inside a specific agent. A developer who installs a different agent, or a lookalike, brings none of your rules with them. That is the gap the AI Agent Blocklist closes.

What we listExamples from our fileWhere you block it
Command-line coding agents by package name@anthropic-ai/claude-code, @openai/codexPackage proxies and endpoint rules
Agent processescursor-agent, geminiIntune, Jamf, Defender
Editor extensions, AI editors, MCP serversThousands of IDs and names in the full fileEditor policies and MDM
Agent domains2,600+ AI agent domainsFirewall, DNS filter, gateway
Write the rule into policy too. Our AI agent acceptable use policy includes wording on secrets, and agent identity and permissions covers giving agents their own scoped credentials. MCP servers need the same care; see the MCP security checklist.

Rules for the agents you allow, a block for the rest

The AI Agent Blocklist covers coding agents, AI editors, MCP servers, AI browsers and agent extensions, with a risk grade on every entry.

From $99 a month for one organisation. Download access is set up within one business day of your order.

See plans Ask a question
  • Package and process names of coding agents
  • Bundle IDs and package IDs for Intune and Jamf
  • Extension IDs for VS Code and JetBrains
  • Domains in firewall, DNS, hosts and PAC formats
  • CSV and JSON, updated every day

Ask us or order a plan

Tell us what you need to block and where your rules live. We reply within one business day.

  • Files for firewalls, DNS filters, secure web gateways, MDM and browser policies
  • Updated every day as new AI browsers, agents and extensions appear
  • Plans for one organisation, for MSPs and for product makers, or a hosted filter we run for you

We use your details only to answer you. No newsletters.

Questions about agents and secrets

How do I prevent Claude Code from reading .env files?
Add Read deny rules such as Read(./.env) and Read(./.env.*) to permissions.deny, ideally in managed settings. They cover Claude's file tools and common file commands in the shell. For a block that also covers scripts and other subprocesses, turn on the sandbox and add the paths to sandbox.filesystem.denyRead.
Does .claudeignore stop Claude Code reading files?
No. Claude Code's documentation says a .claudeignore file has no effect. Move its entries into Read deny rules in your settings.
How do I prevent Codex from reading .env files?
Admins can add a deny_read list under [permissions.filesystem] in requirements.toml, for example /**/*.env and ~/.ssh, which users cannot override. Developers can also add a deny entry for **/*.env in a permission profile. These rules govern the sandboxed commands Codex runs.
How do I prevent Claude Code or Codex from reading certain files?
Use the same mechanisms with your own paths. In Claude Code, write Read deny rules with gitignore-style patterns and add sandbox denyRead paths. In Codex, list the paths in deny_read or in a permission profile. Test each rule with a dummy file before you rely on it.
Is .cursorignore a security control?
No. Cursor's documentation calls it a convenience, not a security boundary. Terminal commands and MCP tools can still read ignored files, so keep secrets out of the workspace and require approval for terminal commands.
Can an agent still see secrets in environment variables?
Yes, if they are set in the shell that starts the agent, because commands it runs inherit them. Keep long-lived tokens out of shell profiles, and use the agent's own controls, such as Claude Code's sandbox credential settings or Codex's shell environment policy, to strip them.
Should .env files be in the project folder at all?
Ideally not with real values. Keep an example file with dummy values in the repository, and load real credentials at run time from a secret manager. Then a missed rule exposes only placeholders, and agents can still learn which settings the app expects.
What is the safest way to keep secrets from coding agents?
Do not keep them where the agent works. Load short-lived credentials at run time from a secret manager, keep production credentials off developer machines, and use deny rules and sandboxes as a second line rather than the only one.

Claude Code is a trademark of Anthropic, PBC. Codex is a trademark of OpenAI. Cursor is a trademark of Anysphere, Inc. GitHub and GitHub Copilot are trademarks of GitHub, Inc.

Gemini is a trademark of Google LLC. Intune, Defender and Windows are trademarks of Microsoft Corporation. Jamf is a trademark of Jamf.

macOS is a trademark of Apple Inc. VS Code is a trademark of Microsoft Corporation. ChatGPT is a trademark of OpenAI. JetBrains is a trademark of JetBrains s.r.o. Linux is a registered trademark of Linus Torvalds.

Names are used only to identify the products discussed. AI Agent Blocklist is not affiliated with, sponsored or endorsed by these companies.