Deleting a leaked key in your next commit does not remove it. The key is still in history, and bots scrape public repos for new keys within minutes. The only reliable fix is to stop the commit before it happens.

Git has a hook for that. A pre-commit script runs before every commit, and a non-zero exit code cancels it. The script below scans only the staged lines, so it stays fast on large repos.

What it looks for

  • AWS access key IDs (AKIA or ASIA plus 16 characters)
  • Private key blocks
  • GitHub, Slack, Stripe and Google tokens, which all have recognizable prefixes
  • Assignments like api_key = "..." with a long literal value
  • Connection strings with a password in them, like postgres://user:pass@host

It skips lines containing words like example, placeholder or changeme, so your README snippets do not trip it.

The script

#!/usr/bin/env python3 import re, subprocess, sys RULES = [ ("AWS access key id", re.compile(r"\b(AKIA|ASIA)[0-9A-Z]{16}\b")), ("Private key block", re.compile(r"-----BEGIN (RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY")), ("GitHub token", re.compile(r"\bgh[pousr]_[A-Za-z0-9]{36,}\b")), ("Slack token", re.compile(r"\bxox[abprs]-[A-Za-z0-9-]{10,}")), ("Stripe live key", re.compile(r"\b(sk|rk)_live_[A-Za-z0-9]{16,}")), ("Google API key", re.compile(r"\bAIza[0-9A-Za-z_\-]{35}\b")), ("Generic secret assignment", re.compile( r"""(?i)\b(api[_-]?key|secret|token|passw(or)?d)\b\s*[:=]\s*['"][^'"\s]{12,}['"]""")), ("Connection string with password", re.compile(r"[a-z]+://[^:/\s]+:[^@/\s]{6,}@")), ] SAFE = re.compile(r"(?i)example|placeholder|changeme|dummy|xxxx|<[^>]+>") def mask(s): return re.sub(r"([A-Za-z0-9_\-/+=]{4})[A-Za-z0-9_\-/+=]{4,}", r"\1****", s) diff = subprocess.run(["git", "diff", "--cached", "-U0"], capture_output=True, text=True, check=True).stdout hits, path = 0, None for raw in diff.splitlines(): if raw.startswith("+++ b/"): path = raw[6:] elif raw.startswith("+") and not raw.startswith("+++"): text = raw[1:] if SAFE.search(text): continue for label, rx in RULES: if rx.search(text): hits += 1 print(f"[{label}] {path}: {mask(text.strip())[:120]}") break sys.exit(1 if hits else 0) 

Install it

Save the file as .git/hooks/pre-commit and run chmod +x .git/hooks/pre-commit. From now on, a commit with a match stops and prints the file and a masked version of the line.

The masking matters. A scanner that prints the full secret to your terminal, your CI log or an AI agent's chat history has just leaked it a second time.

What it will get wrong

It is a regex scanner, so expect both kinds of error.

  • False positives: a test fixture with a fake token that looks real. Add a word like example to that line, or skip the hook once with git commit --no-verify after you have checked the line yourself.
  • False negatives: a secret with no known prefix and no key = style name. Entropy-based tools like gitleaks or trufflehog catch more of these, and they are the better choice for a team. This script is the 35-line version for a solo project.

Also remember that the hook lives in .git/hooks, which is not committed. Teammates do not get it unless you share it through a tool like pre-commit or a core.hooksPath setting.

If it fires on a real key

Do not just remove the line and recommit. Rotate the key first, at the provider, because anything you pasted into a chat or a screenshot is also exposed. Then remove it from the code and move it to an environment variable.

Which key format did I miss that you have seen leak?

This post was written with help from an AI assistant. The script was tested on staged files with planted fake keys before posting.