How do you find, remove and prevent API key and password leaks from AI coding agents?
You find leaked API keys and passwords by scanning three places with a free scanner such as Gitleaks or TruffleHog: the AI agent's log files, your Git history and GitHub. You remove them by rotating each key or password first and deleting every copy. You prevent the next leak by blocking the agent from reading secrets.
How does one Friday evening leak a startup's payment key?
Priya is a developer at a 20-person fintech startup in Pune. On a Friday evening she asks an AI coding agent to fix a failing payment test. The agent reads the project's .env file, copies the live payment-gateway secret key into the test, and commits the fix to a public demo repository.
Priya and the startup are fictional. Every event marked Real world is real and linked to its source.This guide follows one key through one evening at one startup. Every chapter shows where Priya's key went, one real event, the command to run, and one line you can repeat to your team. Answer the check in each chapter to score yourself.
Priya's key: leaked · livePriya's key: found in 5 placesPriya's key: rotated · safe Score 0
Part 1 · How keys leak
Four chapters: the ways a key escapes, who is watching, where copies hide, and how malware uses your agent.
How do API keys leak through AI coding agents?
API keys leak through AI coding agents in five ways: you paste a key into the chat, the agent reads a .env file, the agent writes the key into code, the agent commits that code, or a tool config file (MCP) stores the key in plain text.
Each copy can travel further: to the AI provider with your prompt, into log files on your laptop, into Git history and onto GitHub.
- In Priya's repo
- Priya never typed the key. The agent opened .env to understand the payment settings, printed the secret key in its reply, and pasted it into the test file so the test would pass.
- Real world
- In 2025 GitGuardian found 24,008 unique secrets in MCP configuration files on public GitHub; 2,117 of them were still valid when checked. Source: GitGuardian, State of Secrets Sprawl 2026
- Do this
- Never paste a real key into an agent chat. Give the agent a fake key in a .env.example file and keep the real one where the agent cannot read it (chapter 12).
Which lines of an AI agent session expose the key?
Priya's Friday session, line by line. Tap every line where the payment key escapes. Five do; three are safe.
0/5 found
-
> fix the failing payment testSafe: Priya's request names no key.
Safe: Priya's request names no key.
-
Read README.mdSafe: The README holds no secrets.
Safe: The README holds no secrets.
-
Read .env → PAY_SECRET=sk_live_51Hx…Leak: Reading .env puts the key into the conversation, which goes to the AI provider and into the agent's log.
Leak: Reading .env puts the key into the conversation, which goes to the AI provider and into the agent's log.
-
The test fails because PAY_SECRET (sk_live_51Hx…) is not passed to the client.Leak: The agent printed the key in its reply: it is now in the transcript on disk.
Leak: The agent printed the key in its reply: it is now in the transcript on disk.
-
Edit tests/test_pay.py: api_key = "sk_live_51Hx…"Leak: The key is now hard-coded in a source file.
Leak: The key is now hard-coded in a source file.
-
Run npm test → 12 passedSafe: Test output with no key printed is safe.
Safe: Test output with no key printed is safe.
-
git commit -m "fix payment test" && git pushLeak: The commit carries the key into Git history and onto GitHub.
Leak: The commit carries the key into Git history and onto GitHub.
-
.mcp.json → "env": { "PAY_TOKEN": "sk_live_51Hx…" }Leak: MCP config files store tokens in plain text, and often get committed.
Leak: MCP config files store tokens in plain text, and often get committed.
All five found: one key, five copies, from one request.
Explain it to your team"An AI coding agent copies whatever it sees, so a key it reads can end up in the chat, the logs, the code and Git."
Who scans GitHub for leaked API keys, and how fast?
Automated bots scan every new public GitHub commit for keys, and honeypot studies show leaked cloud keys being used within one to five minutes of the push.
GitHub also scans public commits and forwards keys from partner providers, such as AWS, OpenAI and Anthropic, so the provider can revoke them. Attackers do not wait for that.
- In Priya's repo
- Priya's fix lands in the public demo repository at 7:12 pm. She closes her laptop. Nobody at the startup sees the key until Monday.
- Real world
- Comparitech's honeypot: AWS keys published on GitHub were abused about one minute later, and the whole attack took under four minutes. Palo Alto Networks Unit 42 saw the EleKtra-Leak campaign start within five minutes of keys going up on GitHub. Source: Comparitech · Dark Reading on Unit 42
- Do this
- Treat any key pushed to a public repository as stolen the moment it lands. Rotate it first; investigate afterwards.
How quickly is a leaked key on GitHub found and used?
Drag the clock forward from the moment of the push and see what published honeypot studies recorded.
The commit is public. Every new public commit is scanned by bots.
- 0 min: The commit is public. Every new public commit is scanned by bots.
- 1 min: About 1 minute: attackers found the AWS key and started using it (Comparitech honeypot).
- 4 min: Under 4 minutes: the whole Comparitech attack was done, starting with the largest servers available.
- 5 min: About 5 minutes: Unit 42 saw the EleKtra-Leak campaign start using keys pushed to GitHub.
- 7 min: 7 minutes: more than 400 API calls in the Unit 42 study, all through a VPN.
- 10 min: By now, assume the key is used. Rotating it is the only fix (chapter 9).
Explain it to your team"Bots read every public commit within minutes, so a key pushed in public is a stolen key."
Where do AI coding agents like Claude Code and Codex keep copies of your secrets?
AI coding agents keep copies of what they read in local log files: Claude Code in ~/.claude/projects and Codex in ~/.codex/sessions. The key also stays in your project files, your Git history and every remote you pushed to.
Claude Code's documentation says that if a tool reads a .env file or a command prints a credential, the value is written to the session transcript, and transcripts are not encrypted at rest. Claude Code deletes transcripts after 30 days by default (the cleanupPeriodDays setting).
Where should you look for each copy of a leaked key?
Tap a layer of the stack to see where it lives, the command that checks it, and the chapter that cleans it.
Project files
Where: The project folder, including .env and files Git ignores.
Check with: gitleaks dir . -v
Clean up: Move real keys into a secrets manager →
Agent logs
Where: ~/.claude/projects and ~/.codex/sessions on your computer.
Check with: gitleaks dir ~/.claude -v
Git history
Where: Every commit on every branch of the repository.
Check with: gitleaks git -v
GitHub
Where: The repository on GitHub and its pull requests.
Check with: trufflehog git https://github.com/OWNER/REPO --results=verified
Clean up: Force-push the rewritten history →
Forks and clones
Where: Every teammate's clone and every fork of the repository.
Check with: GitHub: the repository's Insights → Forks page
Clean up: Ask owners to delete and re-clone →
- In Priya's repo
- After one evening Priya's key sits in five places: .env, the test file, a Claude Code transcript, a commit, and the GitHub repository.
- Real world
- Claude Code's official directory reference: a credential that a tool reads or a command prints is written to projects/<project>/<session>.jsonl under ~/.claude. Codex writes each session to ~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl (moved by the CODEX_HOME setting). Source: Claude Code docs, .claude directory · OpenAI Codex issue 2288
- Do this
- Before you scan, list the places on your own machine: the project folder, each agent's log folder, Git history, every remote and every fork.
Mac or Linux: list agent log folders
ls -la ~/.claude/projects ~/.codex/sessionsWindows PowerShell: list agent log folders
Get-ChildItem $env:USERPROFILE\.claude\projects, $env:USERPROFILE\.codex\sessionsExplain it to your team"A leaked key is never in one place: check the project, the agent's logs, Git history and GitHub."
Can malware use your AI coding agent to steal your keys?
Yes. In August 2025 poisoned versions of the Nx build tool ran the AI coding agents already installed on developers' machines, with their permission checks switched off, and told them to hunt for keys and crypto wallets.
The malware started Claude Code with --dangerously-skip-permissions, Gemini CLI with --yolo and Amazon Q with --trust-all-tools. Any key saved in a plain-text file on the laptop was within reach.
- In Priya's repo
- Priya's laptop also holds cloud keys in ~/.aws and a GitHub token, all in plain text. One bad package install could hand every one of them to an agent working for someone else.
- Real world
- 26 August 2025: malicious Nx versions were published to npm. When the GitHub CLI was signed in, the stolen data was uploaded to new public repositories named s1ngularity-repository in the victim's own account. Source: Socket · Snyk
- Do this
- Never run an agent with its permission checks switched off on a machine that holds real keys. Keep keys in a password manager or secrets vault, not in plain-text files.
Check your GitHub account for repositories the Nx malware creates
gh repo list --limit 500 | grep -i s1ngularityExplain it to your team"Malware can drive your AI agent, and plain-text keys on your laptop are the first thing it takes."
Part 2 · Find every copy
Scan your laptop, your Git history and GitHub, and pick the right scanner.
How do you scan your computer for API keys left by AI coding agents?
Run a free secret scanner over the agent's log folders and your project folder: gitleaks dir ~/.claude scans Claude Code's logs, gitleaks dir ~/.codex scans Codex's, and trufflehog filesystem scans the same folders and tests whether each key still works.
Scan the project folder too, including files Git ignores such as .env. The scanner prints the file and line of each finding; it changes nothing, so it is safe to run.
- In Priya's repo
- Priya's scan of ~/.claude finds the payment key twice in one transcript: once where the agent read .env, and once in the reply it printed.
- Real world
- GitGuardian's 2026 report found that commits co-written by AI coding assistants leak secrets at about twice the overall rate on public GitHub. Source: SC Media on GitGuardian 2026
- Do this
- Install Gitleaks (brew install gitleaks, or the release download for Windows) and scan the agent folders and every project folder you have opened with an agent.
Mac or Linux: scan Claude Code and Codex logs
gitleaks dir ~/.claude -v
gitleaks dir ~/.codex -vWindows PowerShell: the same scan
gitleaks dir "$env:USERPROFILE\.claude" -v
gitleaks dir "$env:USERPROFILE\.codex" -vScan the project folder, including ignored files such as .env
gitleaks dir . -vShow only keys that still work (TruffleHog)
trufflehog filesystem ~/.claude ~/.codex --results=verifiedExplain it to your team"Scan the agent's log folders, not just the code: that is where the agent's copy of a key sits."
How do you scan a Git repository's whole history for secrets?
Run gitleaks git inside the repository, or trufflehog git file://. --results=verified, to scan every commit, because a key deleted in a later commit is still stored in the earlier one.
Scan every copy that matters: your laptop clone, the repository on GitHub and any fork. TruffleHog's verified mode lists only keys that still work, which tells you what to rotate first.
- In Priya's repo
- Priya's Monday commit removed the key from the test file, but gitleaks git finds it in Friday's commit, with the commit hash, file, line and author.
- Real world
- GitGuardian counted 28.65 million new hardcoded secrets in public GitHub commits in 2025, up 34% in a year: the largest jump in the report's history. Source: GitGuardian, State of Secrets Sprawl 2026
- Do this
- Scan the full history of every repository an agent has committed to, starting with public ones. Keep the report: it lists every commit you will need to rewrite in chapter 10.
Gitleaks: every commit in this repository
gitleaks git -vTruffleHog: only keys that still work
trufflehog git file://. --results=verifiedTruffleHog: a repository on GitHub
trufflehog git https://github.com/OWNER/REPO --results=verifiedWhich commit in a Git history added the leaked key?
Five commits from Friday to Monday. Tap a commit to scan it by hand, or run Gitleaks to scan them all at once. Two commits added a secret.
-
⚠ tests/test_pay.py:18 payment secret key
-
✓ clean
-
⚠ .mcp.json:6 PAY_TOKEN
-
✓ clean
-
✓ clean · This commit deletes the line, but a1f3c9e still holds the key.
Both found. A scanner reports the commit that added each key; the key stays readable in every later snapshot until the history is rewritten (chapter 10).
Explain it to your team"A new commit hides a key but does not remove it, so scan the whole history."
How do GitHub secret scanning and push protection stop leaked keys?
GitHub secret scanning looks for known key formats in your code. Push protection blocks a push that contains one before it reaches GitHub, and for public repositories GitHub also sends partner keys to the provider, which can revoke them.
Push protection is free for public repositories but must be switched on for each repository or organisation. For private repositories it is part of GitHub Secret Protection: $19 per active committer per month on Team and Enterprise plans.
- In Priya's repo
- With push protection on, Friday's push would have stopped with a message naming the file and line, and the key would never have reached GitHub.
- Real world
- GitHub made push protection free for all public repositories on 9 May 2023. On 13 October 2026 it began blocking Anthropic API keys by default in push protection. Source: GitHub blog, May 2023 · GitHub changelog, Oct 2026 · GitHub Secret Protection pricing
- Do this
- In each repository open Settings, then the security section, and switch on secret scanning and push protection. For an organisation, switch them on for every repository at once.
Explain it to your team"Push protection stops a key at GitHub's door, but only if you switch it on."
Which secret scanner should you use: Gitleaks, TruffleHog, detect-secrets or GitHub?
Use Gitleaks for fast free scans and a pre-commit hook, TruffleHog when you need to know which keys still work, detect-secrets when a team wants a reviewed list of known findings, and GitHub push protection to block keys at the server. Most teams run one local scanner plus push protection.
No scanner finds every key: each matches known patterns, and a key in an unusual format can slip through. Two scanners that work differently catch more than one.
- In Priya's repo
- Priya's startup picks Gitleaks as a pre-commit hook on every laptop, TruffleHog every week across all repositories, and push protection on GitHub.
- Real world
- Attackers use the same tools. In September 2025 the Shai-Hulud npm worm ran TruffleHog on infected developer machines to collect keys, then published them in new public GitHub repositories named Shai-Hulud. Source: Krebs on Security · Trend Micro
- Do this
- Pick one local scanner for laptops and one scheduled scan for all repositories, and switch on push protection. Write the choice down so every new hire sets up the same three.
| Tool | Scans folders | Scans Git history | Tests if the key works | Blocks a commit or push | Cost and licence |
|---|---|---|---|---|---|
| Gitleaks | Yes (gitleaks dir) | Yes (gitleaks git) | No | Commit, via pre-commit hook | Free, open source (MIT) |
| TruffleHog | Yes (filesystem) | Yes (git) | Yes (--results=verified) | Commit, via pre-commit hook | Free, open source (AGPL-3.0) |
| detect-secrets | Yes (current files) | No | No | Commit, via pre-commit hook | Free, open source (Apache-2.0) |
| GitHub secret scanning | No (only what you push) | Yes, on GitHub | Partner keys go to the provider | Push (push protection) | Free on public repos; $19 per committer a month for private |
Which secret scanner setup fits your team?
Tick what you need. The setup below updates as you tick.
Explain it to your team"One scanner on every laptop, one on every repository, and push protection on GitHub."
Part 3 · Fix and prevent
Rotate, rewrite history, clean the agent's logs, and block the next leak.
What should you do first when an API key leaks?
Revoke or rotate the key at its provider first, before cleaning anything: create a new key, switch your app to it, then delete the old one. Then check the provider's usage logs for calls you did not make.
Deleting the file or rewriting Git history does not make a leaked key safe, because copies may already be saved elsewhere. Only revoking it does.
- In Priya's repo
- Monday, 9 am: Priya opens the payment gateway's dashboard, creates a new secret key, deploys it, deletes the old one, and downloads the weekend's API log to look for test charges she did not make.
- Real world
- xAI, 2025: a staff member committed an API key to a public repository on 2 March. GitGuardian emailed the same day, yet the key, with access to at least 60 private and fine-tuned models, stayed live until it was reported to xAI on 30 April. GitGuardian's 2026 report found 64% of valid secrets found in 2022 still not revoked. Source: Krebs on Security · GitGuardian disclosure · GitGuardian 2026
- Do this
- Keep a one-page list of every key your company uses, who owns it and how to rotate it, so the first hour goes on rotating, not searching.
Example, AWS: switch off a leaked access key at once
aws iam update-access-key --user-name USER --access-key-id AKIA... --status InactiveExplain it to your team"Rotate first and clean later: deleting a key never un-leaks it."
How do you remove a secret from Git history?
Use git filter-repo with --sensitive-data-removal and --replace-text to rewrite every commit that holds the secret, force-push the rewritten history, then have everyone re-clone, because old clones and forks still hold it.
Rewriting changes the hash of every later commit and breaks commit signatures. Forks keep the old commits until their owners delete them, and GitHub Support removes cached pull-request views only when rotating the key cannot fix the risk.
- In Priya's repo
- Priya writes the old key into a file outside the repository, runs git filter-repo, confirms gitleaks git finds nothing, force-pushes, and asks the two other developers to delete their clones and clone again.
- Real world
- GitHub's own guide lists four steps: rewrite the history locally, update GitHub, clean up other clones, and prevent it happening again. The --sensitive-data-removal flag needs git-filter-repo 2.47 or later. Source: GitHub Docs: removing sensitive data
- Do this
- Rewrite history only after the key is rotated. Write the leaked values in a text editor, one per line, in a file outside the repository, never with echo, which saves the key in your shell history.
Rewrite every commit (git-filter-repo 2.47 or later; ../secrets.txt lists the leaked values)
git filter-repo --sensitive-data-removal --replace-text ../secrets.txtConfirm the history is clean
gitleaks git -vPush the rewritten history (add the origin remote back first if filter-repo removed it)
git push --force --mirror originExplain it to your team"Rotate the key, rewrite the history, force-push, and make everyone re-clone; forks keep the old copy."
How do you delete secrets from AI coding agent logs?
Delete the session files your scan flagged: Claude Code transcripts under ~/.claude/projects and Codex session files under ~/.codex/sessions. Then scan the folders again to prove the key is gone.
Claude Code deletes transcripts older than 30 days on its own (the cleanupPeriodDays setting), but a leaked key should not wait 30 days. Deleting a session file only removes that conversation from your history.
- In Priya's repo
- Priya deletes the one Friday transcript that held the key, runs gitleaks dir ~/.claude again, and gets zero findings.
- Real world
- Claude Code's documentation says transcripts and history in ~/.claude are not encrypted at rest; operating-system file permissions are the only protection. Source: Claude Code docs, .claude directory
- Do this
- Delete only the files the scanner named, not the whole folder, then rescan. On shared or company laptops, set a shorter cleanupPeriodDays.
Mac or Linux: delete one flagged file (use the exact path the scanner printed)
rm ~/.claude/projects/PROJECT/SESSION.jsonlWindows PowerShell: the same
Remove-Item "$env:USERPROFILE\.claude\projects\PROJECT\SESSION.jsonl"Rescan to confirm
gitleaks dir ~/.claude -vKeep Claude Code transcripts for 7 days: add to ~/.claude/settings.json
{ "cleanupPeriodDays": 7 }Explain it to your team"Delete the agent's log files that hold the key, then rescan to prove they are gone."
How do you stop AI coding agents from reading .env files?
Add deny rules for each agent: in Claude Code, permissions.deny entries such as Read(./.env) in .claude/settings.json; in Codex, a deny-read rule for .env files in its permissions profile; in Cursor, a .cursorignore file; in GitHub Copilot, a content exclusion set by an admin.
These rules cover the agent's file-reading tools, not every command: an agent that runs cat .env in a shell can still see the file, so also turn on the agent's sandbox. The safest .env is one with no real keys in it.
- In Priya's repo
- Priya's team commits a .claude/settings.json that blocks .env and the secrets folder for every developer's agent, and moves real keys into the company's secrets manager.
- Real world
- Deny rules are a layer, not a wall: GitHub issues in 2025 and 2026 reported Claude Code deny rules for .env not being enforced in some cases, and Cursor's forum notes that .cursorignore does not stop terminal commands such as cat. Source: Claude Code issue 6699 · Cursor forum · Claude Code permissions
- Do this
- Use the deny rules, and still keep real keys out of files the agent can open: load them at run time from a secrets manager.
Claude Code: .claude/settings.json in the project
{
"permissions": {
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)"
]
}
}Cursor: .cursorignore in the project root
.env
.env.*
secrets/What settings stop an AI coding agent from reading secret files?
Pick your agent and what to protect. Copy the file it builds into your project.
Explain it to your team"Tell the agent which files are off limits, and keep real keys out of files it can open anyway."
How do you stop secrets before every commit?
Install a pre-commit hook that runs Gitleaks on every commit, switch on GitHub push protection, run a scheduled secret scan in CI, and keep real keys in a secrets manager so they are never in files at all.
A pre-commit hook runs on the developer's laptop and can be skipped; push protection and a CI scan are the checks that cannot be skipped. Short-lived keys limit the damage when one still slips through.
- In Priya's repo
- Six weeks later an agent writes a new test key into a file. Priya's pre-commit hook stops the commit and prints the file and line; nothing reaches GitHub.
- Real world
- November 2025: the Shai-Hulud 2.0 worm compromised hundreds of npm packages, including packages from Zapier, ENS Domains, PostHog and Postman, to steal developers' credentials. Keys on laptops are targets, not just keys in repositories. Source: Zscaler · Sysdig
- Do this
- Add the hook to every repository, the CI scan to every pipeline and push protection to every GitHub organisation, and give every key an owner and an expiry date.
.pre-commit-config.yaml in the repository
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.26.0
hooks:
- id: gitleaksInstall the hook (autoupdate moves rev to the latest release)
pip install pre-commit
pre-commit autoupdate
pre-commit installWhat goes on a leaked-key checklist for teams using AI coding agents?
Leaked-key checklist · AI coding agents
When a key leaks (today)
- Rotate or revoke the key at its provider
- Check the provider's logs for calls you did not make
- Scan agent logs: ~/.claude, ~/.codex
- Scan the project, including .env
- Scan the full Git history of every affected repository
- Rewrite history, force-push, everyone re-clones
- Delete flagged agent log files and rescan
So it does not happen again (this week)
- Deny .env and secrets/ in every agent's settings
- Real keys in a secrets manager, not in files
- Gitleaks pre-commit hook in every repository
- Push protection on in every GitHub organisation
- Weekly TruffleHog scan of all repositories
- Never run agents with permission checks off
- A key list: owner, rotation steps, expiry
From shinifrontiers.com/solvers/coding-agent-secrets-guide
Explain it to your team"Block keys at three doors: the laptop hook, GitHub push protection and the CI scan."
Can you explain the leaked-key response to your team?
Put the six steps of a leaked-key response in order, first step first. If you can, you can teach it.
Tap the lines below one by one, first step first.
- Rotate or revoke the key at its provider
- Check the provider's logs for calls you did not make
- Scan the agent's logs, the project and the Git history
- Rewrite Git history and force-push; everyone re-clones
- Delete the agent's log files that hold the key, then rescan
- Block .env from the agent; add the hook and push protection
What is the leaked-key response, in one minute?
AI coding agents copy what they read, so a key in .env can end up in the chat, the agent's logs, the code and GitHub, where bots find it within minutes. When it happens, rotate the key first, check the provider's logs, then scan the agent's logs, the project and the Git history; rewrite the history, delete the flagged logs and rescan. To stop the next one, deny .env to the agent, keep real keys in a secrets manager, and block keys at three doors: the pre-commit hook, push protection and a CI scan.
ShiniFrontiers · Problem Solver
/100
I can explain how to find and remove API keys leaked through AI coding agents
Can you contain a leaked API key before the bots use it?
A live drill. One of three incidents starts at random; tap the response steps in the right order before the 60-second clock runs out. A wrong step costs 10 seconds.
Time left60
Steps done0/0
Priya and the startup are fictional; every dated event is real and linked to its source. Tool commands and paths are as documented in November 2026; check each tool's current documentation before relying on them.