How to Check Your Git Repository for Leaked Secrets
A secret that reached a commit is still there after you delete the file. Git keeps history, and anyone who clones the repo can read it. So the first question after a leak is not "how do I delete it?" but "what has already been exposed?"
This guide walks through a practical check you can run in under an hour.
Step 1: Scan the full history, not just the latest commit
Most people look at the current files. That misses everything that was committed and later removed. Use a scanner that reads every commit:
# Example with gitleaks, scanning all commits on all branches
gitleaks detect --source . --log-opts="--all"
Other tools such as TruffleHog do the same job. Pick one, run it on a clean clone, and save the output.
Step 2: Search for the usual suspects
Even without a scanner, you can search history for common patterns:
git log -p --all -S "DATABASE_URL"
git log -p --all -S "AWS_SECRET_ACCESS_KEY"
git log --all --diff-filter=A --name-only | grep -E "\.env$|\.pem$|\.key$"
The last command lists every .env, .pem, or .key file ever added. If one appears, check whether it was ever pushed.
Step 3: Check branches, tags, and forks
--all covers branches, but not every reference. Look at tags and remote branches too:
git for-each-ref
If the repository is public or has forks, assume every commit is copied. Forks are not affected by a force push to the main repo.
Step 4: Rotate before you rewrite
Rewriting history removes the value from new clones, but it does not make the secret safe again. Anyone who already pulled it still has it. Rotate every credential that appeared in the scan first, then clean up history.
Rotation order:
- Generate a new value in the provider.
- Update the running services that use it.
- Confirm the old value no longer works.
- Revoke the old value.
Step 5: Clean up history, then tell the team
Once the secret is rotated, you can remove it from history with git filter-repo or the BFG Repo-Cleaner. Both rewrite every commit that touches the file. Every collaborator then needs to re-clone or reset their local copy.
Keep a short record: what leaked, where, when it was rotated, and who was notified. This is the part teams skip, and it is the part that matters the next time.
Prevent the next one
- Add
.env*and key file patterns to.gitignorebefore the first commit. - Run a secret scanner in CI so leaks fail the build.
- Keep real values out of the repo entirely. Store them in an encrypted environment variable manager and pull them at runtime.
A clean scan today is useful. A repo that never holds secrets in the first place is better.
