"""secret-scanner — regex-pattern secret detection, ported from PinkyAI's
own `rules::secrets` engine module (see README.md "Provenance").
Six literal, well-known secret shapes: AWS access keys, GitHub PATs, Slack
tokens, JWTs, PEM private-key blocks, and DB connection strings with an
embedded password. Pure stdlib (`re` only) — no network call, no dependency,
safe to run against untrusted input.
Honest scope (see README.md for the full version): this is a shape check,
not a validity check. It cannot tell a live credential from a revoked or
fake one, and — like any regex-based scanner — it only catches a secret in
its plain, literal form. It exists to catch the common case: a real secret
typed or pasted in as-is, not a deliberately obfuscated one.
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from dataclasses import dataclass
from pathlib import Path
SKIPPED_DIR_NAMES = {".git", "node_modules", "target", "dist", "build", ".venv", "venv", "__pycache__"}
_PATTERNS: list[tuple[str, str, re.Pattern[str]]] = [
("aws_access_key", "critical", re.compile(r"\bAKIA[0-9A-Z]{16}\b")),
("github_pat", "critical", re.compile(r"\bghp_[A-Za-z0-9]{36}\b")),
("slack_token", "high", re.compile(r"\bxox[baprs]-[0-9A-Za-z-]{10,72}\b")),
("jwt", "high", re.compile(r"\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+")),
(
"private_key_block",
"critical",
re.compile(r"-----BEGIN\s+((RSA|EC|OPENSSH|DSA|ENCRYPTED)\s+)?PRIVATE\s+KEY-----"),
),
(
"connection_string",
"critical",
re.compile(r"\b(postgres|postgresql|mysql|mongodb(\+srv)?)://[^\s:@/]+:[^\s@]+@[^\s/]+"),
),
("github_fine_grained_pat", "critical", re.compile(r"\bgithub_pat_[0-9A-Za-z_]{60,}\b")),
("anthropic_api_key", "critical", re.compile(r"\bsk-ant-[A-Za-z0-9_-]{20,}\b")),
("anthropic_oauth_access_token", "critical", re.compile(r"\bsk-ant-oat01-[A-Za-z0-9_-]{20,}\b")),
("anthropic_oauth_refresh_token", "critical", re.compile(r"\bsk-ant-ort01-[A-Za-z0-9_-]{20,}\b")),
("openai_project_key", "critical", re.compile(r"\bsk-proj-[A-Za-z0-9_-]{20,}\b")),
("openai_api_key", "critical", re.compile(r"\bsk-[A-Za-z0-9]{48}\b")),
("google_api_key", "high", re.compile(r"\bAIza[0-9A-Za-z_-]{35}\b")),
("stripe_secret_key", "critical", re.compile(r"\b[sr]k_live_[0-9A-Za-z]{24,}\b")),
]
@dataclass(frozen=True)
class Finding:
rule_id: str
severity: str
path: str
line: int
column: int
redacted: str
def to_dict(self) -> dict[str, object]:
return {
"rule_id": self.rule_id,
"severity": self.severity,
"path": self.path,
"line": self.line,
"column": self.column,
"match": self.redacted,
}
def redact_match(raw: str) -> str:
"""Shows enough of a match to identify it, never enough to use it: the
first 4 and last 4 characters, `***` in between. Anything under 10
characters is fully masked instead — too short for a partial reveal to
mean anything but not too short to still be a real secret (short
connection-string passwords are the case this guards).
"""
if len(raw) < 10:
return "*" * len(raw)
return f"{raw[:4]}***{raw[-4:]}"
def scan_text(text: str, *, path: str = "<stdin>") -> list[Finding]:
"""Scans `text` line-by-line (so findings carry a useful line number)
against every pattern. Pure, no I/O.
"""
findings: list[Finding] = []
for line_no, line in enumerate(text.splitlines(), start=1):
for rule_id, severity, pattern in _PATTERNS:
for match in pattern.finditer(line):
findings.append(
Finding(
rule_id=rule_id,
severity=severity,
path=path,
line=line_no,
column=match.start() + 1,
redacted=redact_match(match.group(0)),
)
)
return findings
def _iter_scannable_files(root: Path):
if root.is_file():
yield root
return
for path in root.rglob("*"):
if not path.is_file():
continue
if any(part in SKIPPED_DIR_NAMES for part in path.parts):
continue
yield path
def scan_path(root: Path) -> list[Finding]:
"""Walks `root` (a file or directory) and scans every text file found.
Binary files are skipped (decode failure), not treated as errors — a
scanner that crashes on the first binary asset in a repo is worse than
one that quietly skips what it can't read as text.
"""
findings: list[Finding] = []
for path in _iter_scannable_files(root):
try:
text = path.read_text(encoding="utf-8")
except (UnicodeDecodeError, OSError):
continue
findings.extend(scan_text(text, path=str(path)))
return findings
def _print_human(findings: list[Finding]) -> None:
if not findings:
print("secret-scanner: no matches for the 6 patterns this tool checks (see README's honest-scope note).")
return
for f in findings:
print(f"[{f.severity}] {f.rule_id} — {f.path}:{f.line}:{f.column} — {f.redacted}")
print(f"\n{len(findings)} finding(s). Rotate any credential this confirms is real before continuing.")
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="Scan text/files for likely-real secrets.")
parser.add_argument("path", nargs="?", help="File or directory to scan")
parser.add_argument("--stdin", action="store_true", help="Scan piped stdin instead of a path")
parser.add_argument("--json", action="store_true", help="Print findings as JSON instead of text")
args = parser.parse_args(argv)
if args.stdin:
findings = scan_text(sys.stdin.read())
elif args.path:
findings = scan_path(Path(args.path))
else:
parser.error("provide a path or --stdin")
return 2
if args.json:
print(json.dumps([f.to_dict() for f in findings], indent=2))
else:
_print_human(findings)
return 1 if findings else 0
if __name__ == "__main__":
sys.exit(main())