Quick answer: Good secret scanning combines two signals. Regex rules catch tokens with a known format (AWS keys, GitHub tokens, Stripe keys, private key headers) with very few false positives. Shannon entropy catches random-looking strings that no rule knows about. Scan the full Git history, not just the latest commit, and scan CI logs and artifacts too, because that is where secrets leak most quietly.
I'm Muhammad Ali Mughal, a Principal Software Engineer in Karachi. I build the free developer tools at PixelValut. In Part 1 we handled the first hour after a leak. This part is about finding leaks you don't know about yet, in repositories and pipelines you own. I wrote it with help from AI tools and checked the patterns against provider documentation and gitleaks' default rules.
📚 Series Navigation — Leaked Secrets: Detect, Rotate, Recover
- Part 1: You Leaked an API Key in Git: The First 60 Minutes
- Part 2 (This Post): Scanning Repos and CI Logs for Secrets With Regex and Entropy
- Part 3: Rotating Secrets Without Downtime: Dual Keys and Overlap Windows (coming next)
- Part 4: Secrets in Container Images and Build Logs
- Part 5: Pre-Commit and CI Guards That Stop the Next Leak
- Part 6: Post-Incident Review: Proving a Leaked Key Was Never Used
Related earlier posts: Webhook Security in Production: HMAC-SHA256 Signatures · Break-Glass Accounts & SSO Audit Logs
Where secrets actually hide
When I audit a client's repositories, the main branch is rarely the problem. These places are:
- Old commits. A key added and removed two years ago is still in history and still valid more often than you'd expect.
- CI logs. A
set -x, a debugenvdump, or a failing curl that prints its own headers writes the secret to logs that many people can read and that are kept for months. - Config samples.
.env.examplefiles where someone pasted the real value "just for now". - Test fixtures and notebooks. Recorded HTTP responses, Jupyter outputs and Postman exports.
- Build artifacts. Bundled front-end JavaScript with a server key baked in at build time (Part 4 goes deeper).
A scanner that only checks staged files misses all of these.
Signal one: format-aware regex rules
Many providers publish token formats with fixed prefixes, which makes them easy to match precisely. A few rules I always include:
| Secret type | Example pattern (simplified) | False-positive risk | Notes |
|---|---|---|---|
| AWS access key ID | A[KS]IA[0-9A-Z]{16} | Low | Pair with a nearby 40-char secret for confidence |
| GitHub token | gh[pousr]_[A-Za-z0-9]{36,} | Very low | Prefixes identify token type |
| Stripe secret key | sk_live_[0-9a-zA-Z]{24,} | Very low | Add a matching sk_test_ rule at lower severity |
| Slack token | xox[baprs]-[0-9A-Za-z-]{10,} | Low | Includes bot and user tokens |
| Private key block | -----BEGIN [A-Z ]*PRIVATE KEY----- | Very low | Always a finding |
| JWT | eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+ | Medium | Many are expired test tokens |
| Generic assignment | api_?key\s*[:=]\s*['"][^'"]{16,} | High | Needs entropy filter |
I test every rule against known-good and known-bad samples before adding it. The PixelValut Regex Tester is handy for this: paste a sample config and see exactly what each pattern catches. Use fake values that only look like real ones, never a live key.
Signal two: Shannon entropy
Custom internal tokens, random passwords and many SaaS keys have no prefix. What they share is randomness. Shannon entropy measures how unpredictable each character is. English words and variable names score low; random base64 or hex strings score high.
Rough guide from my own scans:
- Normal identifiers and words: about 2.5–3.5 bits per character
- Hex secrets (32+ chars): about 3.7–4.0
- Base64 secrets (20+ chars): about 4.5–6.0
The thresholds depend on the alphabet, so I compute entropy separately for hex-only and base64-like strings.
A small scanner you can run today
This scans every line ever added in Git history, applies rules, then falls back to entropy for long random-looking strings. It's intentionally short so you can read and adapt it.
import math, re, subprocess, sys from collections import Counter RULES = { "aws_key_id": re.compile(r"\b(AKIA|ASIA)[0-9A-Z]{16}\b"), "github_token": re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b"), "stripe_secret": re.compile(r"\bsk_(live|test)_[0-9a-zA-Z]{24,}\b"), "private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), } CANDIDATE = re.compile(r"['\"=:\s]([A-Za-z0-9+/_\-]{24,})['\"\s]?") ALLOW = re.compile(r"(EXAMPLE|dummy|test_fixture|0{16,})", re.I) def entropy(s: str) -> float: counts = Counter(s) return -sum(c / len(s) * math.log2(c / len(s)) for c in counts.values()) def scan_history(): log = subprocess.run( ["git", "log", "-p", "--all", "--no-color", "--unified=0"], capture_output=True, text=True, errors="replace", ).stdout commit = None for line in log.splitlines(): if line.startswith("commit "): commit = line.split()[1][:10] continue if not line.startswith("+") or line.startswith("+++"): continue if ALLOW.search(line): continue for name, rx in RULES.items(): if rx.search(line): yield commit, name, line[:120] for m in CANDIDATE.finditer(line): tok = m.group(1) limit = 3.7 if re.fullmatch(r"[0-9a-f]+", tok) else 4.5 if entropy(tok) >= limit: yield commit, f"entropy {entropy(tok):.2f}", line[:120] findings = list(scan_history()) for f in findings: print(*f, sep=" | ") sys.exit(1 if findings else 0) Two notes. First, print only a truncated line, and never send findings to a third-party service; your scan output is now sensitive. Second, for real CI use I'd run an established tool such as gitleaks or trufflehog and keep a script like this for custom internal token formats they don't know.
Scanning CI logs
Most CI platforms let you download logs through their API. I pull the last 30 days of logs for each repo and run the same rules over them. For GitHub Actions:
gh run list --limit 100 --json databaseId -q '.[].databaseId' | while read id; do gh run view "$id" --log > "logs/run-$id.txt" 2>/dev/null done python3 scan_files.py logs/ GitHub masks registered secrets as *** in logs, but only exact values it knows about. A secret that was base64-encoded, URL-encoded or split across lines gets printed in full. That's why I also decode suspicious base64 blobs during review; the Base64 tool works locally in the browser for a quick look, but only use it on values you've already decided to rotate.
Keeping false positives manageable
A scanner nobody trusts gets ignored. What has worked for me:
- Allowlist by path and pattern, not by disabling rules:
tests/fixtures/, lockfiles, and known example values. - Fingerprint accepted findings. Store a hash of the finding (file + rule + matched value hash), not the value, so known false positives don't come back every run.
- Separate severities. Provider-format hits block the build; entropy-only hits create a review task.
- Review weekly at first. After two or three weeks of tuning, noise usually drops a lot.
Diagnostic checklist
- [ ] Full history of every repo (
--all, including old branches and tags) scanned at least once. - [ ] Provider-format rules for every service you actually use.
- [ ] Entropy check with separate thresholds for hex and base64.
- [ ] CI logs for the last 30+ days scanned, plus artifacts.
- [ ] Findings stored as hashes, not raw values.
- [ ] Every confirmed finding triggers the Part 1 rotation runbook.
- [ ] Allowlist reviewed and justified, no blanket ignores.
- [ ] Scan scheduled to run again, not only once.
FAQ
Should I use gitleaks, trufflehog or my own script?
Use an established tool as your main scanner. They have hundreds of tested rules, and trufflehog can verify whether some keys are live. Keep a small custom script for internal token formats.
Does scanning the history mean I have to rewrite it?
No. Rotate first. Rewriting history is optional cleanup and only worth it for some cases, as Part 1 explained.
What entropy threshold should I use?
Start with about 4.5 for base64-like strings and 3.7 for hex, at 24+ characters, then tune on your own repos.
Are JWTs in tests a problem?
Usually not if they're signed with a test key and expired. Check the exp claim with a JWT decoder and allowlist them by path.
How often should I scan?
Every push in CI for new commits, plus a full history and log scan weekly or monthly.
Is it safe to paste findings into an AI assistant to triage?
Don't paste real secret values anywhere. Share the rule name, file path and a masked value.
What's next
Part 3 covers rotating secrets without downtime, using dual keys and overlap windows so a rotation never becomes an outage.
Follow & Connect
- Website: PixelValut Tools
- Watch on YouTube: Resume Boost AI · PixelValut · Daily AI News By Ali
- TikTok: PixelValut (@pixelvalut007)
- X: Muhammad Ali Mughal (@AliMughal887)
- GitHub: Muhammad Ali Mughal (@ali111887)
- LinkedIn: Muhammad Ali Mughal



