Why the secret comes first
A deleted file lives on in old commits: git show HEAD~1:.env prints it whole. After a push, a copy of the history is
on GitHub, with everyone who ran clone or fetch, in forks, and in the pull request cache. Bots scan public
repositories for tokens within minutes. Rewritten history only protects future clones.
So the order is:
- Change the secret where it was issued: a new database password, a revoked Cloudflare token, a new key. The old value stops working, and the leak no longer opens anything (Secrets in Docker stacks).
- Remove the file from the repository and add it to
.gitignore(.gitignore and a tracked file). - If needed, clean the history.
How to clean
The commit isn’t pushed yet — rewrite your own history without affecting anyone:
git rm --cached .env
echo ".env" >> .gitignore
git add .gitignore
git commit --amend --no-edit # if the secret is in the last commit
If it’s deeper — git rebase -i back to the commit with the secret.
Already on GitHub — git filter-repo (a separate program: pip install git-filter-repo, or the git-filter-repo
package on Ubuntu) rewrites the whole history:
git filter-repo --invert-paths --path .env # remove the file from every commit
git filter-repo --replace-text <(echo 'Kx9…==>***REMOVED***') # replace a string everywhere
git push --force --all
After cleaning, every commit has a new hash: everyone else needs a fresh clone. GitHub keeps serving the old commits
by direct hash for a while — GitHub support removes them completely on request.
So it doesn’t happen again
.gitignorebefore the first commit (Git from scratch), and an allowlist in server repositories (Server configs in git).git diff --stagedbefore every commit.- GitHub push protection — on for public repositories, it rejects a
pushcontaining tokens of known services. The rejection gives the secret type, the commit and the file line:—— GitHub Personal Access Token ——,commit: 8728dbe67,path: README.md:4.