Someone commits a .env file, notices ten minutes later, deletes it in the next commit, and everyone relaxes. The file is gone from the working tree. It is not gone from the repository. Every clone still carries the commit that added it, and git log -p will print the key for anyone who asks.

A secret scanner will find that key. But a scanner hit is a lead, not a verdict. The questions that actually decide what you do next are: is this a real credential, does it still work, and where else does it live? This post walks through answering those on your own repository with two open-source tools, then fixing it in the right order.

Scope note before we start: only scan repositories you own or are authorized to assess. Verification (step 3) sends each candidate credential to its provider's API, which is exactly what you want for your own keys and exactly what you must not do with anyone else's.

Why "I deleted it" doesn't help

You can see the problem in under a minute. Make a throwaway repo, commit a fake token, then delete it:

git init demo && cd demo printf 'GITHUB_TOKEN=ghp_FAKE0example0TOKEN0for0docs0only0x9Q\n' > .env git add .env && git commit -m "add config" git rm .env && git commit -m "remove secret" git log --all --oneline -S ghp_ 
86f47c9 remove secret 44894ef add config 

The working tree is clean, yet both commits still hold the string: one adds it, one removes it. Branches you forgot about, tags and stashes can hold it too. That's why a scan of the current files (or a quick look at the latest diff) gives you false comfort. You need to scan history, across all refs.

Step 1: Find candidates with gitleaks

Gitleaks scans git history with regex rules plus entropy checks. When you run gitleaks git with no extra options, it shells out to git log -p -U0 --full-history --all, so every branch and tag is covered, and a deleted file is still caught at the commit that added it.

gitleaks git -v --redact \ --report-format json --report-path gitleaks.json . 

A few things worth knowing:

  • --redact masks the secret in the terminal and in the report. Keep it on. Scan output tends to end up in CI logs and tickets, and you don't want the scan itself to become the second leak.
  • --log-opts replaces the defaults. If you pass your own git log options (say, a commit range), gitleaks stops adding --all. Add it back yourself if you still want every ref.
  • Exit code 1 means "leaks or an error." That makes it easy to fail a CI job, but check the log before you assume a finding.
  • Every finding has a Fingerprint (commit:file:rule:line). You can put fingerprints of reviewed false positives in .gitleaksignore, or save today's report and pass it as --baseline-path later so only new findings show up.

One maintenance note: the gitleaks README now says the project is feature complete and future releases will be security patches only (the latest release is v8.30.1, March 2026). It still works fine for this job; just don't wait for new features.

What gitleaks gives you is a list of strings that look like secrets. It does not tell you whether any of them work. A fake value in a test fixture and a live production key look the same in this report.

Step 2: Ask a second tool, and let it check the keys

The OWASP Secrets Management Cheat Sheet suggests running more than one detection tool and de-duplicating the results, because each tool's rules have different blind spots. For a second opinion I use TruffleHog, because it adds the part gitleaks doesn't do: for each detected credential type, it tries the credential against the provider's API.

Run it from the parent directory (cd .. first), pointing at the local repo:

trufflehog git file://demo --json > trufflehog.jsonl 

By default it reports three kinds of result, and the difference between them matters more than anything else in this post:

Status What TruffleHog means What you should do
verified The provider's API accepted the credential Treat as a live incident: rotate now
unknown Verification was attempted but failed (network or API error) Re-run, or check by hand; assume live until shown otherwise
unverified Detected, not confirmed valid. It may be invalid, expired, or verification may be off Not "safe". Decide by hand

That last row is the trap. "Unverified" doesn't mean "dead". A token for an internal service, or a password the scanner can't reach from where it runs, can't be confirmed by any outside check, and it may be the most dangerous thing in the repo.

If you can't let a scan make outbound calls (an air-gapped runner, or a policy against it), --no-verification turns the checks off and you're back to a candidate list.

Step 3: Turn the output into a rotation list

TruffleHog writes one JSON object per finding, and the same key often appears in several commits. What you want is one line per credential, sorted by urgency, with nothing secret printed. This script does that. It reads the fields TruffleHog's JSON printer writes (Verified, VerificationError, DetectorName, Raw/RawV2 and the git metadata) and puts results in the buckets the way TruffleHog's own engine does: verified first, then anything with a verification error, then the rest.

import hashlib import json import sys ORDER = {"verified": 0, "unknown": 1, "unverified": 2} def status(r): # Same order TruffleHog's engine uses to sort results into --results buckets if r.get("Verified"): return "verified" if r.get("VerificationError"): return "unknown" return "unverified" def main(path): keys = {} with open(path, encoding="utf-8") as fh: for line in fh: if not line.strip(): continue r = json.loads(line) git = r["SourceMetadata"]["Data"]["Git"] # One rotation item per credential, however many commits it appears in key_id = hashlib.sha256((r.get("RawV2") or r["Raw"]).encode()).hexdigest()[:10] item = keys.setdefault(key_id, { "detector": r["DetectorName"], "status": status(r), "error": r.get("VerificationError", ""), "seen": [], }) item["seen"].append(f'{git["file"]}:{git["line"]} @ {git["commit"][:8]}') if ORDER[status(r)] < ORDER[item["status"]]: item["status"] = status(r) for key_id, item in sorted(keys.items(), key=lambda kv: ORDER[kv[1]["status"]]): print(f'[{item["status"].upper():10}] {item["detector"]:12} key#{key_id}') for where in item["seen"]: print(f" {where}") if item["error"]: print(f' verification error: {item["error"]}') if __name__ == "__main__": main(sys.argv[1]) 

Here's its output on a stand-in report in TruffleHog's JSON format (fake keys, fake commits):

[VERIFIED ] Stripe key#83c167c0e2 app/settings.py:12 @ 9f3c2a1b app/settings.py:12 @ 77aa88bb [UNKNOWN ] Slack key#a755302e78 scripts/notify.sh:3 @ 0d0e0f10 verification error: dial tcp: lookup slack.com: i/o timeout [UNVERIFIED] Github key#39b236c8ba config/.env:1 @ 44894ef0 

The key# is a short hash of the secret, so you can talk about "key#83c167c0e2" in a ticket without pasting the key itself. Then go back to the gitleaks report and add anything TruffleHog didn't flag at all, marked "unverified, check by hand".

From scanner hit to fix: scan all refs, run a second tool, ask the provider which keys work, then revoke, check logs, maybe rewrite history, and add a hook and CI check

This is the same principle I apply to any finding: detection isn't proof. The regex says "this looks like a key". The provider's API saying "yes, that key works" is the proof, and it's what moves an item from the backlog to an incident.

Step 4: Fix it in the right order

Rotate or revoke first. GitHub's documentation on removing sensitive data says this outright: if the sensitive data is a credential, revoking or rotating it is the first step, and once it's done that may be enough. History cleanup can take days of coordination. Revocation takes minutes and ends the risk.

Then check whether it was used. Look at the provider's access logs for that key between the commit date (it's in the scan output) and the moment you revoked it. A verified key that sat in a public repo for months is a different conversation from one that lived ten minutes on a private branch.

Then decide whether to rewrite history. For a revoked key, rewriting may not be worth it. If the data itself is sensitive (a customer export, a private key you can't simply rotate), GitHub's guide uses git-filter-repo (version 2.47 or later for the flag below):

git-filter-repo --sensitive-data-removal --invert-paths --path config/.env 

Go in with eyes open. The same guide lists the side effects: every commit hash after that point changes, commit signatures are dropped, collaborators with old clones can push the data straight back, forks keep their copy, and GitHub only removes cached views and pull-request references if you contact Support. A rewrite reduces exposure; it doesn't undo it.

Step 5: Stop the next one at the commit

Two cheap guards catch most repeats.

A pre-commit hook, so the secret never becomes a commit. Gitleaks ships a hook definition for the pre-commit framework, and it scans only staged changes, with redaction on:

# .pre-commit-config.yaml repos: - repo: https://github.com/gitleaks/gitleaks rev: v8.30.1 hooks: - id: gitleaks 

A CI check on every branch, in case someone skips the hook (SKIP=gitleaks git commit … is one environment variable away). TruffleHog's README shows scanning just the commits a branch adds on top of main:

trufflehog git file://. --since-commit main --branch HEAD \ --results=verified,unknown --fail 

With --fail, it exits with code 183 when it finds results, which fails the job. Limiting the CI gate to verified,unknown keeps it from blocking on every test fixture. Run the full, everything-included scan on a schedule and triage it by hand instead.

And for the long run, the OWASP cheat sheet's advice applies: keep secrets in a secrets manager, prefer short-lived credentials, and make rotation something you can do in minutes, because sooner or later you'll need to.

Try it yourself

  • The throwaway repo above. Recreate the demo repo from the first section, run gitleaks git -v --redact . inside it, and confirm the deleted token is found at commit "add config". Then run a scan with --log-opts="HEAD~1..HEAD" and watch what happens when you narrow the range.
  • OWASP WrongSecrets. A training game made of real-life examples of how not to store secrets, each one a challenge you solve with different tools; its README also offers it as a test bed for secret scanners. Run it locally with docker run -p 8080:8080 -p 8090:8090 jeroenwillemsen/wrongsecrets:latest-no-vault and open http://localhost:8080.
  • Your own repositories. Start with the oldest one you still maintain. Old repos predate today's habits, and their keys are the ones nobody remembers.

As always: only scan and verify credentials in repos you own or are authorized to test.

Wrapping up

Deleting a secret hides it from the working tree and nowhere else. Scan the full history across all refs, use a second tool, and let the provider tell you which keys still work. Rotate the verified and unknown ones first, check the logs, and only then decide whether rewriting history is worth the cost. Finally, put a hook and a CI check in place so the next leak is caught before it becomes a commit.

Further reading

I'm Krishna, a pentester and the founder of Xalgorix, an open-source AI pentester that only reports vulnerabilities it has actually exploited.

🔐 If this was useful, follow me for more hands-on web & API security write-ups.

🔗 Connect with me on LinkedIn: https://www.linkedin.com/in/xalgord/