Guide
How to keep API keys away from AI agents
Published
AI agents can read your project files and run commands, and chatbots keep everything you paste. A key that reaches the model can end up in a request to a website, especially when that website asks for one. These steps keep your keys out of reach.
1. Don’t paste real keys into a chat
A placeholder like PAYMENTS_API_KEY=xxx gives the model all the context it needs. If you have already pasted a real key, rotate it with the service that issued it.
2. Block your agent from reading secret files
- Claude Code: add Read deny rules, for example
"deny": ["Read(./.env)", "Read(./.env.*)"]in.claude/settings.json. Anthropic’s docs say these cover Claude’s file tools and commands likecat, but not scripts that open files themselves. - Cursor:
.env*files are ignored by default for Agent, Tab and @ mentions. The agent’s terminal can still read them, so don’t rely on this alone. - Codex: set
ignore_default_excludes = falseunder[shell_environment_policy]so variables named withKEY,SECRETorTOKENare removed from the commands Codex runs. It’strueby default, per OpenAI’s config docs.
3. Limit the network
An agent can only send a key to a website it can reach.
- Claude Code: turn on the Bash sandbox with
/sandbox. Commands then reach only domains you allow. - Codex: local commands have no network by default. Leave it off unless a task needs it.
- Cursor: avoid the Run Everything run mode and keep
curlandwgetoff any allowlist, so network commands come to you first.
4. Read network commands before you approve them
Look for keys, tokens, Authorization headers and file contents in curl, wget and script commands. If a command sends a secret you didn’t mean to share, deny it and tell the agent why.
5. Keep secrets out of the project when you can
Load secrets from a secret manager or your shell at run time instead of keeping them in a .env inside the folder the agent works in. For untrusted projects, run the agent in a container or VM: see how to reduce what your AI coding agent can access.
6. Test your setup
Settings are easy to get wrong. The API key leak test uses a fake key to show what your AI actually sends to a website that asks for one.
Find out in about a minute. Free, no sign-up, results deleted after 1 hour.
Run the Agent Leak Test