Leaked API key or password in a Git repository: rotate first, then clean the history
Once a key is in a repository, assume someone has it, even if the repository is private and the commit was deleted a minute later. Bots scan new public commits within minutes. The order matters: make the key useless first, clean up second.
Revoke or rotate the secret now
Do this before anything else. Create a new key or password in the provider, switch your services to it, then delete the old one. Cleaning the history does nothing if the old key still works.
Check what the key could do and whether it was used
Open the provider's access log or audit trail for the key. Look for calls from addresses and at times you do not recognise, new resources, new users, or unexpected cost.
Find every place the secret lives
Search the working tree and the history, and think about copies: CI logs, forks, container images, backups and chat messages.
git log -p -S'THE_SECRET_PREFIX' --all | head -n 40 grep -rn 'THE_SECRET_PREFIX' . --exclude-dir=.gitRemove it from the history
Rewrite the history with git filter-repo, force push, and ask everyone to re-clone. This is cleanup for tidiness; the key is already considered compromised.
git filter-repo --replace-text <(printf 'THE_SECRET==>REMOVED\n') git push --force --allMove secrets out of the code
Use environment variables, the CI secret store or a secrets manager, and keep a .env example file without real values.
echo '.env' >> .gitignoreTurn on secret scanning and a pre-commit check
Enable the scanning and push protection offered by your Git host, and add a local scanner as a pre-commit hook so a secret is stopped before it leaves the machine.
Common mistakes
- Deleting the file in a new commit: the secret stays in the history.
- Rotating the key but not updating the service that used it, causing an outage.
- Rewriting history without telling the team, who then push the old history back.
- Not checking the provider log, so misuse goes unnoticed.
How to undo it
Rotation is not reversible by design: issue another new key if the first rotation breaks a service. A history rewrite can be reverted from a backup clone you made before filtering.
Sources
Commands are for Debian and Ubuntu unless noted. Test on a copy first and keep a backup: you are responsible for changes on your own systems.