DEV Community

Vildanden
Vildanden

Posted on

Catch a leaked secret in a Claude Code diff with a PostToolUse hook

A PreToolUse write guard can stop Claude Code from overwriting .env. It will not catch a key that already landed in a source file. A PostToolUse hook can scan the current git diff after an Edit or Write and stop the turn before you commit.

The hook should name the problem and exit 2. It should never print the matching value.

The hook

Save this as .claude/hooks/secret_scan.py and make it executable:

#!/usr/bin/env python3
import re
import subprocess
import sys

PATTERNS = [
    r"-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----",
    r"(?i)\b(?:aws_access_key_id|aws_secret_access_key|api[_-]?key|secret[_-]?key|access[_-]?token)\s*[:=]\s*['\"][A-Za-z0-9_\-/.+=]{16,}",
    r"\b(?:sk|pk)_(?:live|test)_[A-Za-z0-9]{16,}\b",
    r"\beyJ[A-Za-z0-9_\-]{20,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\b",
]

def diff_text() -> str:
    try:
        proc = subprocess.run(
            ["git", "diff", "--no-ext-diff", "--unified=0", "HEAD"],
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.DEVNULL,
            timeout=4,
        )
        if proc.returncode != 0:
            proc = subprocess.run(
                ["git", "diff", "--no-ext-diff", "--unified=0"],
                text=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.DEVNULL,
                timeout=4,
            )
        return proc.stdout if proc.returncode == 0 else ""
    except (OSError, subprocess.SubprocessError):
        return ""

text = diff_text()
if any(re.search(pattern, text) for pattern in PATTERNS):
    print("PostToolUse secret scan: the current diff has a high-signal secret shape. Remove or rotate it; do not print the value.")
    sys.exit(2)
print("PostToolUse secret scan passed.")
Enter fullscreen mode Exit fullscreen mode

Wire it in .claude/settings.json under PostToolUse with a matcher of Edit|Write and command set to python3 .claude/hooks/secret_scan.py.

Why this beats a pasted prompt

Hooks run on the event, not when you remember to ask. The patterns above are high-signal shapes only: PEM private-key banners, common cloud key assignments, Stripe-style sk_live / pk_test prefixes, and JWT-shaped tokens. They are routing rules, not a security boundary. Test with inert fixtures such as a fake BEGIN RSA PRIVATE KEY banner in a disposable file. Never paste a real secret into the fixture or the hook output.

Tips

  • Keep the hook local, fast, and free of network calls.
  • Pair it with a PreToolUse write guard and permission deny rules for .env paths so secrets are blocked both before and after the edit.
  • If a legitimate test fixture trips the matcher, narrow the pattern or move the fixture out of the working tree rather than printing the value to debug it.

Want the rest of the setup?

I keep copy-ready Claude Code configs (CLAUDE.md templates, slash commands, hooks, permission rules) in Vildanden Agent Config. There's a free sample: https://justly-mia-429.rehost.page/

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The exit 2 detail is the part I would have missed — a warning that still lets the edit through is barely a safety net, and blocking the tool call is what actually stops the secret from landing in the file. Scanning Edit|Write with a small pattern list (sk_live, pk_test, JWT shapes, BEGIN RSA PRIVATE KEY) and never printing the matching value feels like the right balance of strict and quiet. Have you ever had the hook flag a false positive on a test fixture, or has testing with inert secrets kept that clean so far?