How to Remove Leaked API Keys and .env Files from Git History (git filter-repo Guide)
Originally published at umutgungorr.com. Deleting a leaked .env file in a new commit leaves the secret in Git history. Learn the exact recovery sequence: key rotation, git filter-repo scrubbing, and TokenGuard pre-commi
Originally published at umutgungorr.com.
Deleting a leaked .env file in a new commit leaves the secret in Git history. Learn the exact recovery sequence: key rotation, git filter-repo scrubbing, and TokenGuard pre-commit prevention.
Step 1: Revoke & Rotate the Exposed Key Before Scrubbing History
If the commit reached a public remote, automated scanners may have indexed it within seconds. Running git rm in a follow-up commit keeps the secret readable in earlier commits, so always revoke and rotate the exposed credential first.
Step 2: Scrubbing the File or Secret String with git filter-repo
git-filter-repo is the officially recommended replacement for git filter-branch. You can purge an entire .env file across all commits or replace a leaked token string with ***REMOVED***.
# 1) Taze bir mirror/klon ΓΌzerinde Γ§alΔ±ΕΔ±n
pip install git-filter-repo
# 2a) YanlΔ±ΕlΔ±kla eklenen .env dosyasΔ±nΔ± tΓΌm geΓ§miΕten silme
git filter-repo --path .env --invert-paths --force
# 2b) Veya belirli bir anahtar dizgisini metin olarak maskeleme
# secrets.txt iΓ§eriΔi: sk_live_ORNEK_ANAHTAR==>***REMOVED***
git filter-repo --replace-text secrets.txt --force
# 3) TemizlenmiΕ geΓ§miΕi zorla pushlayΔ±n ve .gitignore'a ekleyin
echo ".env" >> .gitignore
git push --force --all
git push --force --tags
Step 3: Prevent Future Leaks Locally with TokenGuard Pre-Commit
Scrubbing history is incident response; the real fix is blocking secrets locally before git commit completes. TokenGuard scans staged diffs with regex rules and Shannon entropy completely offline.
pip install tokenguard-cli
# Staged dosyalarΔ± commit ΓΆncesi tara
tokenguard scan --staged
# Otomatik Git pre-commit kancasΔ± kur
tokenguard install-hook
References
Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β full credit and traffic to the original publisher.