Security
How to Stop AI Coding Agents From Leaking Your API Keys
Why agent permission files leak passwords to GitHub, a 10-minute repo audit, and a safer setup for Claude Code, Cursor and Copilot.
You approve a shell command from your AI coding agent, it asks again ten minutes later, and eventually you click “allow and don’t ask again” so you can get on with your work. That one click can write the full command, including any password or token you typed into it, into a settings file inside your project. If that file reaches a public repository, your database password is now on GitHub, and automated scanners tend to find it before you notice. This guide shows how the leak happens, how to audit your repositories in about ten minutes, and a safer configuration for Claude Code, Cursor, Copilot and similar agents.
Summary: what to do
- Never type secrets directly into commands you approve. Reference environment variables instead, so saved permission rules store
$DATABASE_URL, not the value. - Add agent folders and local settings files (
.claude/settings.local.json,.cursor/,.gemini/,.specstory/) to every repository’s.gitignore, not only to a global ignore file. - Block commits of those paths with a pre-commit hook that matches on file path, because secret scanners often miss hand-made passwords.
- If a secret was ever committed, rotate it first and clean the history second. Deleting the file does not remove it from history, forks or clones.
- Give agents development keys with minimal scope and low spending limits, and keep production credentials off your laptop.
Background: what the research found
Researchers at Apiiro scanned public GitHub repositories for the permission files that AI coding agents create. According to Cybernews’ coverage of the study, they found more than 104,000 such files committed publicly, 2,539 sensitive secrets across 1,994 repositories, and 1,105 repositories holding live credentials rather than placeholders. Examples included production database passwords, payment-provider tokens and root SSH credentials. Weekly security roundups from CyberPress and CybelAngel placed the finding alongside other attacks aimed at developers who use AI tools, such as infostealers that target AI session tokens and API keys, and “LLMjacking”, where attackers run up model bills on stolen credentials. Agent-focused briefs from AI Agents Directory and AI Agent Store tracked the same period. The gap between “pushed by mistake” and “exploited” keeps getting shorter.
How a permission click becomes a public secret
Take Claude Code, the tool the study focused on. When the agent proposes a shell command, you can deny it, allow it once, or allow it permanently. The permanent option saves an allow rule to .claude/settings.local.json in the project folder, and the rule contains the command text. Approve this once with “don’t ask again”:
psql "postgresql://admin:RealPassword123@db.example.com:5432/prod" -c "select count(*) from orders"
and the connection string, password included, now lives in a JSON file. The same applies to curl -H "Authorization: Bearer sk-...", sshpass -p ..., mysql -p... and any other command with an inline secret.
“But the tool already ignores that file”
Claude Code adds its local settings file to a git ignore list automatically, and the team behind it said, as reported by Cybernews, that the leaked files had been added manually. In practice there are several common gaps:
- Folders that become repositories later. You work with the agent in a plain folder, run
git initafterwards, andgit add .sweeps the file in. - Cloned repositories. Ignore rules do not behave the same way in every repository you clone.
- Files already committed. Adding a path to
.gitignoredoes not remove it from history. - “Commit everything” requests. Asking the agent to stage and commit all changes is exactly how stray files get included.
Why gitleaks and TruffleHog miss some of it
Secret scanners are strong on keys with recognizable formats, such as provider prefixes. A password you made up and typed into a connection string has no pattern to match. That is the class of secret the study highlighted as most often missed, which is why path-based blocking matters later in this guide.
Not only one tool
The same risk exists with Copilot’s auto-approve settings in VS Code, saved chat transcripts, and agent “memory” files. Folders worth checking include .claude/, .cursor/, .gemini/ and .specstory/, plus instruction files such as CLAUDE.md or AGENTS.md if anyone ever pasted credentials into them.
Audit your repositories in ten minutes
Step 1: find tracked agent files
Run this from the root of each repository:
git ls-files | grep -E '(^|/)\.(claude|cursor|gemini|specstory)/'
Open anything it prints. Then check history, because a file removed from the current branch can still sit in older commits:
git log --all --oneline -- '.claude/settings.local.json' '**/.claude/settings.local.json'
Step 2: grep permission files for secret-shaped strings
grep -rEn "(password|passwd|token|secret|apikey|api_key|Bearer |://[^ ]+:[^ ]+@|sshpass|-p[^ ]{4,})" .claude/ .cursor/ 2>/dev/null
The ://user:password@ pattern deserves extra attention: it is the shape of a database connection string with an embedded password.
Step 3: scan full history with a dedicated tool
gitleaks git -v .
Syntax varies between versions, so check gitleaks --help. It will not catch every hand-made password, but it catches most formatted keys.
Step 4: check the hosting platform
On GitHub, open Security > Secret scanning for each public repository. If a repository was ever public and later made private, treat every secret in its history as exposed.
If something leaked: rotate first, clean second
- Revoke and rotate every secret found: API keys, database passwords, SSH keys, service tokens. For databases, also review the list of database users.
- Review usage logs for the exposure window: AI API billing, SSH logins (
last,/var/log/auth.log), database access logs and cloud account activity. - Delete allow rules that contain secrets from the agent’s settings.
- Rewrite history with
git filter-repoor BFG Repo-Cleaner, then force-push. This reduces future exposure but never replaces step 1. - Turn on spending alerts for API and cloud accounts so a missed copy of an old key shows up quickly.
A safer configuration
1. Ignore agent files in every repository
# AI coding agents: local settings, transcripts, memory
.claude/settings.local.json
.claude/*.local.*
.cursor/
.gemini/
.specstory/
*.agent-memory.*
.env
.env.*
!.env.example
If your team shares a common agent config such as .claude/settings.json, commit that file, exclude the .local variants, and review the shared file like any other code. Add a global ignore file as a second layer:
git config --global core.excludesFile ~/.gitignore_global
2. Keep secrets out of command lines
Instead of this:
curl -H "Authorization: Bearer sk-abc123..." https://api.example.com/v1/items
use an environment variable:
curl -H "Authorization: Bearer $EXAMPLE_API_KEY" https://api.example.com/v1/items
Load variables from a secrets manager rather than a plain file. With the 1Password CLI, for example, op run --env-file=.env.tpl -- npm run migrate reads a template containing references such as DATABASE_URL=op://Dev/postgres/url, which is safe to commit. Doppler, Infisical, HashiCorp Vault and cloud secret managers follow the same idea. Then tell the agent the rule in its instruction file:
## Secrets
- Never put passwords, tokens or API keys directly in shell commands.
- Always reference environment variables ($DATABASE_URL, $OPENAI_API_KEY, ...).
- Do not read, print or summarize .env files.
- If a variable is missing, stop and ask. Do not invent values.
3. Deny reads of secret files
Claude Code supports deny rules in settings.json. A reasonable starting point:
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)",
"Read(~/.ssh/**)",
"Read(~/.aws/**)"
],
"allow": [
"Bash(npm run test:*)",
"Bash(npm run lint)",
"Bash(git status)",
"Bash(git diff:*)"
]
}
}
Allow rules should be narrow and value-free: permit npm run test:*, not every psql command. Cursor, Copilot and other agents have equivalent allow and deny lists for terminal commands. Prune them regularly instead of only adding to them.
4. Block at commit time
With the pre-commit framework, .pre-commit-config.yaml:
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: vX.Y.Z # use the current release
hooks:
- id: gitleaks
- repo: local
hooks:
- id: block-agent-files
name: Block AI agent local files
entry: "Do not commit local AI agent files"
language: fail
files: '(^|/)\.(cursor|gemini|specstory)/|settings\.local\.json$'
The second hook blocks by path, so it works even when no scanner recognizes the password inside.
5. Turn on platform protection
Enable secret scanning and push protection in your repository or organization security settings. Push protection stops a git push that contains a recognizable key.
6. Limit the blast radius
- Agents on your machine should see development keys only, with minimal scope and low spending caps.
- Use short-lived, read-only credentials if production access is unavoidable.
- Run agents in a devcontainer, VM or sandbox mode when working on unfamiliar code (take-home tests, client repositories, random clones), with no SSH keys or cloud credentials inside.
- Install agents, plugins and extensions from official sources only, and check the publisher name.
To check whether a specific key format is exposed in text you are about to share, try our free API key leak checker.
FAQ
My repository is private. Do I still need this?
The risk is lower but not zero. Private repositories get made public, shared with contractors, or exposed when a team member’s account is compromised. Secrets do not belong in git either way.
Should I stop using “don’t ask again”?
No. Use it for safe, repetitive commands with no sensitive values, such as tests, linting and git status. For anything with credentials in its arguments, approve once.
Will an agent read my .env file without being asked?
It can, when it explores project configuration to fix an error. That is why a deny rule plus an explicit instruction not to read or print the file is worth adding.
Does switching models change the risk?
Not for this issue. Permission files and git history belong to the agent tool, not the model. If commands pass through a third-party gateway, also review that gateway’s data policy.
How this article was made: this is our own guide and analysis, based on the research coverage and security roundups linked above and on the public documentation of the tools mentioned. Commands and configuration are examples to adapt to your project; test them on a throwaway repository first.
Sources
- Cybernews: Thousands of secrets are slipping into GitHub through AI coding agents
- CyberPress: Weekly Cybersecurity Roundup, November 2-6, 2026
- CybelAngel: Weekly Cyber Roundup, November 2-8
- AI Agents Directory: AI Agents News Brief, November 6, 2026
- AI Agent Store: Daily AI Agent News, November 2026
Written by the CTRL ALT AI team with AI assistance and edited by a person.