Scan files for leaked secrets (cloud, GitHub, Slack, Stripe, Google, AI keys, private keys, high-entropy assignments) with output that never prints the secret. Use when the user asks to check staged files or a repo for secrets before committing.
95%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Medium
Suggest reviewing before use
#!/usr/bin/env python3
"""Scan files for secrets without printing them. Standard library only, Python 3.10+.
A readable port of the ten built-in rules of secrets-precommit, so the skill works without
compiling anything. Findings show at most four leading characters of a secret plus ``****``.
Usage:
python3 scripts/scan_secrets.py [--config FILE] [--format text|json] [--no-defaults]
[--verbose] FILE...
Output (text): ``path:line:column: rule-id: redacted``. Exit codes: 0 nothing found,
1 at least one potential secret, 2 usage, configuration or read error.
Differences from the Go binary: patterns use the Python ``re`` engine (ASCII classes), so team
patterns are limited to RE2-style syntax (no lookaround, no backreferences) and trusted input.
"""
from __future__ import annotations
import argparse
import json
import math
import re
import stat
import sys
from collections import Counter
from dataclasses import dataclass, field
from pathlib import Path
MAX_FILE_SIZE = 1 << 20
SNIFF_SIZE = 8 << 10
MAX_CONFIG_SIZE = 1 << 20
MAX_RULES = 100
MAX_PATTERN_BYTES = 1000
MAX_ID_BYTES = 64
ALLOW_MARKER = "secrets-precommit:allow"
REDACTED_SUFFIX = "****"
MAX_VISIBLE = 4
WRAP_PREFIX = r"(?:^|[^A-Za-z0-9_])("
WRAP_SUFFIX = r")(?:[^A-Za-z0-9_]|$)"
ID_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$")
# Syntax Go's RE2 rejects; refuse it so a team rule behaves the same in both implementations.
NON_RE2_RE = re.compile(r"\(\?(?:[=!]|<[=!]|>|\()|\\[1-9]|\(\?P=")
class ConfigError(Exception):
"""The configuration is invalid."""
@dataclass(frozen=True)
class Rule:
id: str
description: str
pattern: re.Pattern[str]
secret_group: int = 0
min_entropy: float = 0.0
@property
def anchored(self) -> bool:
return self.pattern.pattern.startswith(WRAP_PREFIX)
@dataclass(frozen=True)
class Finding:
rule_id: str
path: str
line: int
column: int
redacted: str
@dataclass
class Settings:
rules: list[Rule] = field(default_factory=list)
allow_paths: list[str] = field(default_factory=list)
allow_regexes: list[re.Pattern[str]] = field(default_factory=list)
def token_rule(rule_id: str, description: str, pattern: str) -> Rule:
compiled = re.compile(WRAP_PREFIX + pattern + WRAP_SUFFIX, re.ASCII)
return Rule(rule_id, description, compiled, secret_group=1)
DEFAULT_RULES: tuple[Rule, ...] = (
token_rule(
"aws-access-key-id",
"AWS access key ID",
r"(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16}",
),
token_rule(
"github-token",
"GitHub personal, OAuth, user, server or refresh token",
r"gh[pousr]_[A-Za-z0-9]{36}",
),
token_rule(
"github-fine-grained-pat",
"GitHub fine-grained personal access token",
r"github_pat_[A-Za-z0-9_]{82}",
),
token_rule("slack-token", "Slack token", r"xox[baprs]-[A-Za-z0-9-]{10,200}"),
token_rule(
"stripe-live-key",
"Stripe live secret or restricted key",
r"(?:sk|rk)_live_[A-Za-z0-9]{24,99}",
),
token_rule("google-api-key", "Google API key", r"AIza[A-Za-z0-9_-]{35}"),
token_rule(
"anthropic-api-key", "Anthropic API key", r"sk-ant-api03-[A-Za-z0-9_-]{93}AA"
),
token_rule(
"openai-api-key",
"OpenAI API key",
r"sk-[A-Za-z0-9_-]{20,}T3BlbkFJ[A-Za-z0-9_-]{20,}",
),
token_rule(
"private-key-block",
"Private key block header",
r"-----BEGIN[ A-Z]*PRIVATE KEY-----",
),
Rule(
"generic-assignment",
"High-entropy value assigned to a key, secret, token or password",
re.compile(
r"""(?i)(?:key|secret|token|password|passwd|api_key)\s*[:=]\s*["']([^"'\s]{12,})["']""",
re.ASCII,
),
secret_group=1,
min_entropy=3.5,
),
)
# --- helpers ---------------------------------------------------------------------------------
def shannon(text: str) -> float:
"""Shannon entropy of the UTF-8 bytes of ``text`` in bits per byte."""
data = text.encode("utf-8")
if not data:
return 0.0
total = len(data)
return -sum((n / total) * math.log2(n / total) for n in Counter(data).values())
def redact(secret: str) -> str:
"""First characters of the secret (at most half, at most four) followed by ``****``."""
shown = min(len(secret) // 2, MAX_VISIBLE)
head = "".join("?" if _is_control(ch) else ch for ch in secret[:shown])
return head + REDACTED_SUFFIX
def _is_control(ch: str) -> bool:
return ord(ch) < 32 or 127 <= ord(ch) < 160
def display_path(path: str) -> str:
"""Quote a path that holds control characters so it cannot drive a terminal."""
if any(_is_control(ch) for ch in path):
return json.dumps(path)
return path
def glob_to_regex(glob: str) -> re.Pattern[str]:
"""Translate a ``path.Match`` style glob (``*``, ``?``, ``[a-z]``, ``\\``) to a regex."""
out: list[str] = []
i = 0
while i < len(glob):
ch = glob[i]
if ch == "*":
out.append("[^/]*")
elif ch == "?":
out.append("[^/]")
elif ch == "\\":
i += 1
if i >= len(glob):
raise ValueError("bad glob")
out.append(re.escape(glob[i]))
elif ch == "[":
i += 1
negate = i < len(glob) and glob[i] == "^"
if negate:
i += 1
parts: list[str] = []
while True:
if i >= len(glob):
raise ValueError("bad glob")
if glob[i] == "]" and parts:
break
lo, i = _class_char(glob, i)
hi = lo
if i < len(glob) and glob[i] == "-":
hi, i = _class_char(glob, i + 1)
if hi < lo:
raise ValueError("bad glob")
parts.append(
re.escape(lo) if lo == hi else f"{re.escape(lo)}-{re.escape(hi)}"
)
out.append("[" + ("^" if negate else "") + "".join(parts) + "]")
else:
out.append(re.escape(ch))
i += 1
return re.compile("".join(out), re.DOTALL)
def _class_char(glob: str, i: int) -> tuple[str, int]:
if i >= len(glob) or glob[i] in "-]":
raise ValueError("bad glob")
if glob[i] == "\\":
i += 1
if i >= len(glob):
raise ValueError("bad glob")
return glob[i], i + 1
# --- configuration -----------------------------------------------------------------------------
def load_settings(config_path: str | None, no_defaults: bool) -> Settings:
cfg: dict[str, object] = {}
if config_path:
raw = Path(config_path).read_bytes()
if len(raw) > MAX_CONFIG_SIZE:
raise ConfigError(f"config exceeds {MAX_CONFIG_SIZE} bytes")
try:
loaded = json.loads(raw.decode("utf-8"))
except (ValueError, UnicodeDecodeError) as err:
raise ConfigError(f"invalid JSON: {str(err)[:200]}") from None
if not isinstance(loaded, dict):
raise ConfigError("config must be a JSON object")
cfg = loaded
unknown = set(cfg) - {"rules", "disableDefaults", "allowlist"}
if unknown:
raise ConfigError(f"unknown field {min(unknown)!r}")
if no_defaults:
cfg["disableDefaults"] = True
return compile_settings(cfg)
def _as_list(value: object, name: str) -> list[object]:
if value is None:
return []
if not isinstance(value, list):
raise ConfigError(f"{name} must be a list")
return value
def compile_settings(cfg: dict[str, object]) -> Settings:
settings = Settings()
team = _as_list(cfg.get("rules"), "rules")
if len(team) > MAX_RULES:
raise ConfigError(f"too many rules: {len(team)} (max {MAX_RULES})")
if not cfg.get("disableDefaults"):
settings.rules.extend(DEFAULT_RULES)
seen = {rule.id for rule in settings.rules}
for index, item in enumerate(team):
rule = build_rule(index, item)
if rule.id in seen:
raise ConfigError(f"rule {rule.id!r}: duplicate id")
seen.add(rule.id)
settings.rules.append(rule)
if not settings.rules:
raise ConfigError("no rules enabled")
allow = cfg.get("allowlist") or {}
if not isinstance(allow, dict) or set(allow) - {"paths", "regexes"}:
raise ConfigError("allowlist must be an object with paths and regexes")
paths = _as_list(allow.get("paths"), "allowlist.paths")
regexes = _as_list(allow.get("regexes"), "allowlist.regexes")
if len(paths) > MAX_RULES or len(regexes) > MAX_RULES:
raise ConfigError(f"too many allowlist entries (max {MAX_RULES} per list)")
for index, glob in enumerate(paths):
if (
not isinstance(glob, str)
or not glob
or len(glob.encode()) > MAX_PATTERN_BYTES
):
raise ConfigError(
f"allowlist path #{index} is empty or exceeds {MAX_PATTERN_BYTES} bytes"
)
try:
glob_to_regex(glob)
except ValueError:
raise ConfigError(f"allowlist path #{index}: invalid glob") from None
settings.allow_paths.append(glob)
for index, expr in enumerate(regexes):
if (
not isinstance(expr, str)
or not expr
or len(expr.encode()) > MAX_PATTERN_BYTES
):
raise ConfigError(
f"allowlist regex #{index} is empty or exceeds {MAX_PATTERN_BYTES} bytes"
)
settings.allow_regexes.append(_compile(expr, f"allowlist regex #{index}"))
return settings
def _compile(expr: str, label: str) -> re.Pattern[str]:
if NON_RE2_RE.search(expr):
raise ConfigError(
f"{label}: lookaround, backreferences and atomic groups are not supported"
)
try:
return re.compile(expr, re.ASCII)
except re.error as err:
raise ConfigError(f"{label}: invalid pattern: {str(err)[:200]}") from None
def build_rule(index: int, item: object) -> Rule:
if not isinstance(item, dict) or set(item) - {
"id",
"description",
"pattern",
"secretGroup",
"minEntropy",
}:
raise ConfigError(f"rule #{index}: unknown or malformed fields")
rule_id = item.get("id")
if (
not isinstance(rule_id, str)
or not ID_RE.match(rule_id)
or len(rule_id) > MAX_ID_BYTES
):
raise ConfigError(
f"rule #{index}: invalid id (use 1-{MAX_ID_BYTES} characters from A-Z a-z 0-9 . _ -)"
)
pattern = item.get("pattern")
if not isinstance(pattern, str) or not pattern:
raise ConfigError(f"rule {rule_id!r}: empty pattern")
if len(pattern.encode()) > MAX_PATTERN_BYTES:
raise ConfigError(
f"rule {rule_id!r}: pattern exceeds {MAX_PATTERN_BYTES} bytes"
)
compiled = _compile(pattern, f"rule {rule_id!r}")
group = item.get("secretGroup", 0)
if (
not isinstance(group, int)
or isinstance(group, bool)
or not 0 <= group <= compiled.groups
):
raise ConfigError(f"rule {rule_id!r}: secretGroup {group} is out of range")
entropy = item.get("minEntropy", 0)
if (
isinstance(entropy, bool)
or not isinstance(entropy, (int, float))
or not 0 <= entropy <= 8
):
raise ConfigError(f"rule {rule_id!r}: minEntropy must be between 0 and 8")
description = item.get("description", "")
return Rule(rule_id, str(description), compiled, group, float(entropy))
# --- scanning ----------------------------------------------------------------------------------
def path_allowed(settings: Settings, name: str) -> bool:
slash = name.replace("\\", "/")
base = slash.rsplit("/", 1)[-1]
for glob in settings.allow_paths:
pattern = glob_to_regex(glob)
if pattern.fullmatch(slash) or pattern.fullmatch(base):
return True
return False
def accept(settings: Settings, rule: Rule, secret: str) -> bool:
if rule.min_entropy > 0 and shannon(secret) < rule.min_entropy:
return False
return not any(rx.search(secret) for rx in settings.allow_regexes)
def scan_line(settings: Settings, name: str, number: int, line: str) -> list[Finding]:
"""Findings of one line. After a match the search restarts at the end of the secret."""
if ALLOW_MARKER in line:
return []
found: list[Finding] = []
for rule in settings.rules:
pos = 0
while pos <= len(line):
match = rule.pattern.search(line[pos:])
if match is None:
break
step = match.end()
start, end = match.span(rule.secret_group)
if start >= 0 and end > start:
if rule.anchored and pos > 0 and start == 0:
pos += 1
continue
secret = line[pos + start : pos + end]
if accept(settings, rule, secret):
found.append(
Finding(rule.id, name, number, pos + start + 1, redact(secret))
)
step = end
pos += max(step, 1)
return found
def scan_text(settings: Settings, name: str, data: bytes) -> list[Finding]:
"""Scan one file's bytes: binary and oversized inputs yield nothing."""
if len(data) > MAX_FILE_SIZE or b"\0" in data[:SNIFF_SIZE]:
return []
text = data.decode("utf-8", errors="replace")
findings: list[Finding] = []
for number, line in enumerate(text.split("\n"), start=1):
findings.extend(scan_line(settings, name, number, line.removesuffix("\r")))
return findings
def scan_file(settings: Settings, name: str, notes: list[str]) -> list[Finding]:
try:
info = Path(name).lstat()
except OSError as err:
raise OSError(f"{name}: {err.strerror or err}") from None
mode = info.st_mode
reason = ""
if stat.S_ISLNK(mode):
reason = "symlink"
elif stat.S_ISDIR(mode):
reason = "directory"
elif not stat.S_ISREG(mode):
reason = "not_regular"
elif info.st_size > MAX_FILE_SIZE:
reason = "too_large"
elif path_allowed(settings, name):
reason = "allowlisted"
if reason:
notes.append(f"skipped {display_path(name)}: {reason}")
return []
try:
with open(name, "rb") as handle:
data = handle.read(MAX_FILE_SIZE + 1)
except OSError as err:
raise OSError(f"{name}: {err.strerror or err}") from None
if b"\0" in data[:SNIFF_SIZE]:
notes.append(f"skipped {display_path(name)}: binary")
return []
return scan_text(settings, name, data)
def sort_key(finding: Finding) -> tuple[str, int, int, str]:
return (finding.path, finding.line, finding.column, finding.rule_id)
# --- command line ------------------------------------------------------------------------------
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
prog="scan_secrets.py",
description="Scan files for secrets; never prints a full secret.",
)
parser.add_argument("files", nargs="*", metavar="FILE")
parser.add_argument("--config", help="JSON file with team rules and allowlists")
parser.add_argument("--format", choices=("text", "json"), default="text")
parser.add_argument(
"--no-defaults", action="store_true", help="disable the built-in rules"
)
parser.add_argument(
"--verbose", action="store_true", help="report skipped files on stderr"
)
try:
args = parser.parse_args(argv)
except SystemExit as exc:
return 0 if exc.code == 0 else 2
prog = "scan_secrets"
if not args.files:
sys.stderr.write(f"{prog}: no files given\n")
return 2
try:
settings = load_settings(args.config, args.no_defaults)
except (ConfigError, OSError) as err:
sys.stderr.write(f"{prog}: {err}\n")
return 2
findings: list[Finding] = []
errors: list[str] = []
notes: list[str] = []
for name in args.files:
try:
findings.extend(scan_file(settings, name, notes))
except OSError as err:
errors.append(str(err))
findings.sort(key=sort_key)
if args.format == "json":
rows = [
{
"ruleId": f.rule_id,
"path": f.path,
"line": f.line,
"column": f.column,
"redacted": f.redacted,
}
for f in findings
]
sys.stdout.write(
json.dumps(rows, separators=(",", ":"), ensure_ascii=False) + "\n"
)
else:
for f in findings:
sys.stdout.write(
f"{display_path(f.path)}:{f.line}:{f.column}: {f.rule_id}: {f.redacted}\n"
)
if args.verbose:
for note in notes:
sys.stderr.write(f"{prog}: {note}\n")
for message in errors:
sys.stderr.write(f"{prog}: {message}\n")
if findings:
sys.stderr.write(
f"{prog}: {len(findings)} potential secret(s) found; "
f"add {ALLOW_MARKER} to a line to suppress it\n"
)
return 1
return 2 if errors else 0
if __name__ == "__main__":
sys.exit(main())