Secret Scanning
GitHub scans your code for leaked credentials and can block pushes that contain them.
Secret scanning looks for tokens, keys, and passwords accidentally committed to your repo. When it finds a known pattern (like an AWS key or a GitHub token) it alerts you β and can even alert the provider to revoke it.
Push protection
With push protection enabled, GitHub blocks a push that contains a detected secret before it ever lands in history.
If a secret leaks
- Revoke and rotate the credential immediately.
- Remove it from history and prevent it recurring with
.gitignore.
Example
# Keep secrets out of Git in the first place
echo ".env" >> .gitignore
# If push protection blocks a secret, remove it, then:
git add .gitignore
git commit -m "Ignore local env file"
# ...and rotate the leaked key with its provider.When to use it
- A developer accidentally commits an AWS key; GitHub's secret scanning detects and alerts the security team within minutes of the push.
- A team enables push protection so Git rejects a commit containing a detected token before it ever reaches the remote.
- A security engineer reviews the secret scanning alerts dashboard to ensure all detected credentials have been rotated and resolved.
More examples
Enable secret scanning via API
Enables both secret scanning (alerts on existing secrets) and push protection (blocks new commits containing secrets) via the API.
gh api repos/{owner}/{repo} \
--method PATCH \
-f security_and_analysis.secret_scanning.status=enabled \
-f security_and_analysis.secret_scanning_push_protection.status=enabledList open secret scanning alerts
Fetches all open secret scanning alerts and extracts the secret type and the GitHub UI link for each one.
gh api repos/{owner}/{repo}/secret-scanning/alerts \
--jq '.[] | select(.state=="open") | {type: .secret_type, url: .html_url}'Pre-commit hook to block secrets locally
A local pre-commit hook runs gitleaks on staged changes and blocks the commit if a credential pattern is found, catching leaks before they push.
# Install trufflehog or gitleaks locally
cat .git/hooks/pre-commit
#!/bin/sh
gitleaks protect --staged --redact --no-banner
if [ $? -ne 0 ]; then
echo 'Secret detected. Commit blocked.'
exit 1
fi
Discussion