How to Scan a Repository for Leaked Secrets
Detect leaked secrets with Gitleaks: scan the working tree and full git history, add a pre-commit hook, and fail CI on findings. Covers the rotate-first incident response for confirmed leaks.
What and why
Committed secrets (API keys, tokens, private keys) are a frequent breach cause, and they persist in git history even after deletion. Secret scanning detects them with pattern and entropy rules so you catch leaks before they reach the remote, and find old ones already there.
Prerequisites
- A git repository.
- A CI provider.
- Basic command line familiarity.
Steps
1. Choose a secret scanner
Gitleaks and TruffleHog are widely used open-source scanners. They detect known credential formats and high-entropy strings. This example uses Gitleaks.
2. Scan the working tree
docker run -v $(pwd):/repo zricethezav/gitleaks:latest detect --source=/repo --no-git
--no-git scans current files; useful before the first commit.
3. Scan git history
gitleaks detect --source=. --redact
This walks every commit. --redact hides the secret value in the report. If you find a real secret in history, rotate it immediately, because anyone with a clone already has it.
4. Add a pre-commit hook
Stop secrets locally before they are committed:
# .pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.0
hooks:
- id: gitleaks
Run pre-commit install so the hook runs on every commit.
5. Gate CI and respond to leaks
Add a CI job that fails the build on any finding:
- uses: gitleaks/gitleaks-action@v2
For a confirmed leak, the response order matters: rotate the credential first (assume it is compromised), then purge it from history with git filter-repo and force-push, and finally add a rule to prevent recurrence.
Verification
- A planted fake key is detected in the working tree.
- The history scan reports any committed secrets.
- The pre-commit hook blocks a commit containing a secret.
- The CI job fails when a secret is present.
Next Steps
Move real secrets into a manager like Vault or your platform's secret store, enable provider-side push protection where available, and add an allowlist with justifications for unavoidable test fixtures.
Prerequisites
- A git repository
- A CI provider
- Basic command line knowledge
Steps
- 1Choose a secret scanner
- 2Scan the working tree
- 3Scan git history
- 4Add a pre-commit hook
- 5Gate CI and respond to leaks