commitwarden 0.1.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ """commitwarden: catch secrets before they're committed."""
2
+ from importlib.metadata import PackageNotFoundError, version
3
+
4
+ try:
5
+ __version__ = version("commitwarden")
6
+ except PackageNotFoundError: # running from a source checkout without installing
7
+ __version__ = "0.0.0+unknown"
commitwarden/allow.py ADDED
@@ -0,0 +1,74 @@
1
+ """Ignore rules: default skips, .commitwardenignore globs, binary sniffing."""
2
+ from __future__ import annotations
3
+
4
+ from fnmatch import fnmatchcase
5
+ from pathlib import Path
6
+
7
+ DEFAULT_SKIP_DIRS = {
8
+ ".git", "node_modules", "vendor", "dist", "build", ".venv", "venv",
9
+ "__pycache__", ".mypy_cache", ".pytest_cache", ".next", "target",
10
+ ".terraform", "Pods",
11
+ }
12
+ DEFAULT_SKIP_FILES = {
13
+ "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock",
14
+ "Cargo.lock", "composer.lock", "Gemfile.lock", "go.sum",
15
+ }
16
+ SKIP_SUFFIXES = (".min.js", ".min.css", ".map", ".lock", ".png", ".jpg",
17
+ ".jpeg", ".gif", ".webp", ".ico", ".pdf", ".zip", ".gz",
18
+ ".woff", ".woff2", ".ttf", ".eot", ".mp4", ".mov", ".wasm")
19
+
20
+
21
+ def load_ignores(root: Path) -> list[str]:
22
+ """Patterns from .commitwardenignore, in order; a leading "!" re-includes a path."""
23
+ f = root / ".commitwardenignore"
24
+ if not f.is_file():
25
+ return []
26
+ pats = []
27
+ for raw in f.read_text(encoding="utf-8", errors="replace").splitlines():
28
+ line = raw.strip()
29
+ if line and not line.startswith("#"):
30
+ pats.append(line)
31
+ return pats
32
+
33
+
34
+ def _default_skip(path: str) -> bool:
35
+ parts = path.split("/")
36
+ return (any(p in DEFAULT_SKIP_DIRS for p in parts[:-1])
37
+ or parts[-1] in DEFAULT_SKIP_FILES
38
+ or path.endswith(SKIP_SUFFIXES))
39
+
40
+
41
+ def _matches(path: str, pat: str) -> bool:
42
+ """gitignore-style: "*.env" matches any basename, "a/b" and "/a" are rooted,
43
+ "dir/" matches only directories, and a matching directory covers what's under it."""
44
+ dir_only = pat.endswith("/")
45
+ rooted = pat.startswith("/") or "/" in pat.rstrip("/")
46
+ pat = pat.strip("/")
47
+ parts = path.split("/")
48
+ # Directories containing the file, then (unless dir-only) the file itself.
49
+ candidates = ["/".join(parts[:i]) for i in range(1, len(parts))]
50
+ if not dir_only:
51
+ candidates.append(path)
52
+ alt = pat[3:] if pat.startswith("**/") else None
53
+ for c in candidates:
54
+ if rooted and fnmatchcase(c, pat):
55
+ return True
56
+ base = c.rsplit("/", 1)[-1]
57
+ if not rooted and fnmatchcase(base, pat):
58
+ return True
59
+ if alt is not None and (fnmatchcase(base, alt) or fnmatchcase(c, alt)):
60
+ return True
61
+ return False
62
+
63
+
64
+ def is_ignored(path: str, extra: list[str]) -> bool:
65
+ ignored = _default_skip(path)
66
+ for pat in extra: # last matching pattern wins, like .gitignore
67
+ neg = pat.startswith("!")
68
+ if _matches(path, pat[1:] if neg else pat):
69
+ ignored = not neg
70
+ return ignored
71
+
72
+
73
+ def looks_binary(data: bytes) -> bool:
74
+ return b"\x00" in data[:8192]
commitwarden/cli.py ADDED
@@ -0,0 +1,229 @@
1
+ """commitwarden CLI."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import re
7
+ import subprocess
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ from . import __version__
12
+ from .allow import is_ignored, load_ignores, looks_binary
13
+ from .detectors import Finding, scan_line
14
+
15
+ EXIT_CLEAN, EXIT_FOUND, EXIT_ERROR = 0, 1, 2
16
+
17
+ # Settings that keep git output parseable whatever the user's config says.
18
+ _GIT_BASE = ["git", "-c", "core.quotePath=false", "-c", "color.ui=never"]
19
+ _COMMIT_MARK = "commitwarden-commit "
20
+ _HUNK = re.compile(r"^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@")
21
+
22
+
23
+ class ScanError(Exception):
24
+ """A problem the user must fix; reported with exit code 2."""
25
+
26
+
27
+ def _git_bytes(*args: str, cwd: Path) -> bytes:
28
+ try:
29
+ proc = subprocess.run([*_GIT_BASE, *args], cwd=cwd, capture_output=True)
30
+ except OSError as exc: # git not installed
31
+ raise ScanError(f"cannot run git: {exc}") from exc
32
+ if proc.returncode != 0:
33
+ msg = proc.stderr.decode("utf-8", "replace").strip()
34
+ raise ScanError(msg or f"git {' '.join(args)} failed")
35
+ return proc.stdout
36
+
37
+
38
+ def _git(*args: str, cwd: Path) -> str:
39
+ return _git_bytes(*args, cwd=cwd).decode("utf-8", "replace")
40
+
41
+
42
+ def _nul_list(out: str) -> list[str]:
43
+ return [p for p in out.split("\0") if p]
44
+
45
+
46
+ def repo_root() -> Path:
47
+ return Path(_git("rev-parse", "--show-toplevel", cwd=Path.cwd()).strip())
48
+
49
+
50
+ def staged_files(root: Path) -> list[str]:
51
+ return _nul_list(_git("diff", "--cached", "--name-only", "-z", "--diff-filter=ACMR",
52
+ "--no-renames", cwd=root))
53
+
54
+
55
+ def all_files(root: Path) -> list[str]:
56
+ return _nul_list(_git("ls-files", "-z", "--cached", "--others", "--exclude-standard",
57
+ cwd=root))
58
+
59
+
60
+ def read_staged(root: Path, path: str) -> bytes:
61
+ return _git_bytes("cat-file", "blob", f":{path}", cwd=root)
62
+
63
+
64
+ def scan_bytes(data: bytes, path: str, use_entropy: bool) -> list[Finding]:
65
+ if looks_binary(data):
66
+ return []
67
+ findings: list[Finding] = []
68
+ # Split on "\n" only, so line numbers match git and editors (str.splitlines also breaks on \f, 
…).
69
+ for i, line in enumerate(data.decode("utf-8", "replace").split("\n"), 1):
70
+ findings.extend(scan_line(line.rstrip("\r"), path, i, use_entropy=use_entropy))
71
+ return findings
72
+
73
+
74
+ def scan_staged(root: Path, extra: list[str], use_entropy: bool) -> list[Finding]:
75
+ out: list[Finding] = []
76
+ for path in staged_files(root):
77
+ if is_ignored(path, extra):
78
+ continue
79
+ out.extend(scan_bytes(read_staged(root, path), path, use_entropy))
80
+ return out
81
+
82
+
83
+ def scan_worktree(root: Path, extra: list[str], use_entropy: bool) -> list[Finding]:
84
+ out: list[Finding] = []
85
+ for path in all_files(root):
86
+ if is_ignored(path, extra):
87
+ continue
88
+ fp = root / path
89
+ # Symlinks may point outside the repository; deleted files are still listed by git.
90
+ if fp.is_symlink() or not fp.is_file():
91
+ continue
92
+ out.extend(scan_bytes(fp.read_bytes(), path, use_entropy))
93
+ return out
94
+
95
+
96
+ def _diff_path(header: str) -> str | None:
97
+ """Path from a "+++ b/path" line; None for "+++ /dev/null"."""
98
+ p = header[4:].rstrip("\t")
99
+ if p.startswith('"') and p.endswith('"'):
100
+ p = p[1:-1]
101
+ return p[2:] if p.startswith("b/") else None
102
+
103
+
104
+ def scan_history(root: Path, extra: list[str], use_entropy: bool,
105
+ max_commits: int | None) -> list[Finding]:
106
+ """Scan lines added by every commit on every ref, with their line numbers in that commit."""
107
+ args = ["log", "-p", "--all", "--unified=0", "--no-color", "--no-ext-diff",
108
+ "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/",
109
+ f"--format=format:{_COMMIT_MARK}%H"]
110
+ if max_commits:
111
+ args.append(f"-n{max_commits}")
112
+ out: list[Finding] = []
113
+ commit, path, line_no = "", None, 0
114
+ for raw in _git(*args, cwd=root).split("\n"):
115
+ raw = raw.rstrip("\r")
116
+ if raw.startswith(_COMMIT_MARK):
117
+ commit, path, line_no = raw[len(_COMMIT_MARK):].strip(), None, 0
118
+ elif raw.startswith("diff --git "):
119
+ path, line_no = None, 0
120
+ elif raw.startswith("+++ "):
121
+ path = _diff_path(raw)
122
+ elif raw.startswith("@@"):
123
+ m = _HUNK.match(raw)
124
+ line_no = int(m.group(1)) - 1 if m else 0
125
+ elif raw.startswith("+"):
126
+ line_no += 1
127
+ if path is None or is_ignored(path, extra):
128
+ continue
129
+ out.extend(scan_line(raw[1:], path, line_no, use_entropy=use_entropy,
130
+ commit=commit))
131
+ return out
132
+
133
+
134
+ def load_baseline(path: Path | None) -> set[str]:
135
+ """Fingerprints from {"fingerprints": [...]} or a list of findings (--json output)."""
136
+ if path is None:
137
+ return set()
138
+ try:
139
+ data = json.loads(path.read_text(encoding="utf-8"))
140
+ except OSError as exc:
141
+ raise ScanError(f"cannot read baseline {path}: {exc.strerror or exc}") from exc
142
+ except json.JSONDecodeError as exc:
143
+ raise ScanError(f"baseline {path} is not valid JSON: {exc}") from exc
144
+ if isinstance(data, dict) and isinstance(data.get("fingerprints"), list):
145
+ items = data["fingerprints"]
146
+ elif isinstance(data, list):
147
+ items = [d.get("fingerprint") if isinstance(d, dict) else d for d in data]
148
+ else:
149
+ raise ScanError(f'baseline {path} must be a list of findings or {{"fingerprints": [...]}}')
150
+ return {str(x) for x in items if x}
151
+
152
+
153
+ def dedupe(findings: list[Finding]) -> list[Finding]:
154
+ """One finding per (path, rule, secret): the first by path, line and commit."""
155
+ seen: set[tuple[str, str, str]] = set()
156
+ out = []
157
+ for f in sorted(findings, key=Finding.sort_key):
158
+ key = (f.path, f.rule, f.fingerprint)
159
+ if key not in seen:
160
+ seen.add(key)
161
+ out.append(f)
162
+ return out
163
+
164
+
165
+ def _positive_int(text: str) -> int:
166
+ try:
167
+ n = int(text)
168
+ except ValueError:
169
+ n = 0
170
+ if n < 1:
171
+ raise argparse.ArgumentTypeError("must be a positive whole number")
172
+ return n
173
+
174
+
175
+ def _to_json(f: Finding) -> dict[str, object]:
176
+ d: dict[str, object] = {"path": f.path, "line": f.line_no, "rule": f.rule,
177
+ "secret": f.redacted, "fingerprint": f.fingerprint}
178
+ if f.commit:
179
+ d["commit"] = f.commit
180
+ return d
181
+
182
+
183
+ def main(argv: list[str] | None = None) -> int:
184
+ ap = argparse.ArgumentParser(prog="commitwarden",
185
+ description="Catch secrets before they're committed.")
186
+ mode = ap.add_mutually_exclusive_group()
187
+ mode.add_argument("--staged", action="store_true", help="scan staged changes (default)")
188
+ mode.add_argument("--all", action="store_true", help="scan tracked + untracked files")
189
+ mode.add_argument("--history", action="store_true", help="scan commit history")
190
+ ap.add_argument("--json", action="store_true", help="machine-readable output")
191
+ ap.add_argument("--baseline", type=Path, help="suppress known fingerprints")
192
+ ap.add_argument("--no-entropy", action="store_true", help="skip entropy-based rules")
193
+ ap.add_argument("--max-commits", type=_positive_int, help="limit history depth")
194
+ ap.add_argument("-q", "--quiet", action="store_true", help="print nothing; use the exit code")
195
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
196
+ args = ap.parse_args(argv)
197
+
198
+ try:
199
+ root = repo_root()
200
+ baseline = load_baseline(args.baseline)
201
+ extra = load_ignores(root)
202
+ use_entropy = not args.no_entropy
203
+ if args.history:
204
+ found = scan_history(root, extra, use_entropy, args.max_commits)
205
+ elif args.all:
206
+ found = scan_worktree(root, extra, use_entropy)
207
+ else:
208
+ found = scan_staged(root, extra, use_entropy)
209
+ except (ScanError, OSError) as exc:
210
+ print(f"commitwarden: {exc}", file=sys.stderr)
211
+ return EXIT_ERROR
212
+
213
+ findings = [f for f in dedupe(found) if f.fingerprint not in baseline]
214
+
215
+ if args.json:
216
+ print(json.dumps([_to_json(f) for f in findings], indent=2))
217
+ elif findings and not args.quiet:
218
+ for f in findings:
219
+ where = f" (commit {f.commit[:10]})" if f.commit else ""
220
+ print(f"{f.path}:{f.line_no} {f.rule} {f.redacted} [{f.fingerprint}]{where}")
221
+ print(f"\n{len(findings)} secret(s) found.", file=sys.stderr)
222
+ elif not args.quiet:
223
+ print("commitwarden: clean.", file=sys.stderr)
224
+
225
+ return EXIT_FOUND if findings else EXIT_CLEAN
226
+
227
+
228
+ if __name__ == "__main__":
229
+ raise SystemExit(main())
@@ -0,0 +1,154 @@
1
+ """Detection rules, entropy, redaction, fingerprinting."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import math
6
+ import re
7
+ from collections import Counter
8
+ from dataclasses import dataclass
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Rule:
13
+ name: str
14
+ pattern: re.Pattern[str]
15
+ group: int = 0
16
+ entropy_floor: float | None = None
17
+ # Loose rules (generic assignments, URLs) also reject placeholders and code references.
18
+ loose: bool = False
19
+ # If set, the "key" group of the match must contain this pattern (checked outside the regex).
20
+ key_filter: re.Pattern[str] | None = None
21
+
22
+
23
+ def _r(name: str, regex: str, group: int | None = None,
24
+ entropy_floor: float | None = None, loose: bool = False,
25
+ key_filter: str | None = None) -> Rule:
26
+ pattern = re.compile(regex)
27
+ if group is None:
28
+ # Secret is the "secret" group, else the first capture group, else the whole match.
29
+ group = pattern.groupindex.get("secret", 1 if pattern.groups else 0)
30
+ kf = re.compile(key_filter, re.IGNORECASE) if key_filter else None
31
+ return Rule(name, pattern, group, entropy_floor, loose, kf)
32
+
33
+
34
+ # Words that make a key name secret-sounding, anywhere in it: STRIPE_SECRET_KEY, dbPassword, x-api-key.
35
+ # Matched against the whole name after the regex, not inside it: searching for a word inside an
36
+ # identifier in the regex itself backtracks quadratically on long runs of identifier characters.
37
+ _SECRET_WORDS = r"api[_\-]?key|secret|token|passw(?:or)?d|pwd|auth|credential|private[_\-]?key"
38
+
39
+ RULES: tuple[Rule, ...] = (
40
+ _r("aws-access-key-id", r"\b(?:A3T[A-Z0-9]|AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16}\b"),
41
+ _r("aws-secret-access-key",
42
+ r"(?i)aws_secret_access_key[\"']?\s*[:=]\s*[\"']?([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])"),
43
+ _r("github-pat", r"\bgh[pousr]_[A-Za-z0-9]{36,255}\b"),
44
+ _r("github-fine-grained-pat", r"\bgithub_pat_[A-Za-z0-9_]{82}\b"),
45
+ _r("gitlab-pat", r"\bglpat-[A-Za-z0-9_\-]{20}\b"),
46
+ _r("slack-token", r"\bxox[abeoprs]-[A-Za-z0-9\-]{10,}\b"),
47
+ _r("slack-webhook",
48
+ r"https://hooks\.slack\.com/services/T[A-Z0-9]+/B[A-Z0-9]+/[A-Za-z0-9]+"),
49
+ # pk_ keys are publishable by design, so only secret (sk_) and restricted (rk_) keys.
50
+ _r("stripe-key", r"\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{16,}\b"),
51
+ _r("google-api-key", r"\bAIza[0-9A-Za-z_\-]{35}(?![0-9A-Za-z_\-])"),
52
+ _r("sendgrid-key", r"\bSG\.[A-Za-z0-9_\-]{22}\.[A-Za-z0-9_\-]{43}(?![A-Za-z0-9_\-])"),
53
+ _r("twilio-key", r"\bSK[0-9a-fA-F]{32}\b"),
54
+ _r("npm-token", r"\bnpm_[A-Za-z0-9]{36}\b"),
55
+ _r("pypi-token", r"\bpypi-[A-Za-z0-9_\-]{50,}"),
56
+ _r("anthropic-key", r"\bsk-ant-[A-Za-z0-9_\-]{20,}"),
57
+ # Classic sk-… and project/service-account keys (sk-proj-…, sk-svcacct-…); not Anthropic's sk-ant-.
58
+ _r("openai-key", r"\bsk-(?!ant-)(?:proj-|svcacct-|admin-)?[A-Za-z0-9_\-]{20,}"),
59
+ _r("private-key-block",
60
+ r"-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?-----"),
61
+ _r("jwt", r"\beyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}"),
62
+ _r("db-url-with-password", r"\b[a-z][a-z0-9+.\-]{0,30}://[^:@/\s]+:([^@/\s]{4,})@", loose=True),
63
+ _r("bearer-token", r"(?i)\bbearer\s+([A-Za-z0-9_\-.=+/]{20,})",
64
+ entropy_floor=3.5, loose=True),
65
+ _r("generic-assignment",
66
+ r"(?<![\w.\-])(?P<key>[\w.\-]+)[\"']?\s*(?::=|=>|[:=])\s*[\"'`]?"
67
+ r"(?P<secret>[A-Za-z0-9_\-+/=.]{12,})",
68
+ entropy_floor=3.5, loose=True, key_filter=_SECRET_WORDS),
69
+ )
70
+
71
+ MAX_LINE = 20_000
72
+ MAX_SECRET = 4_096
73
+
74
+ _PLACEHOLDER_WORDS = ("example", "changeme", "change_me", "placeholder", "your_", "your-",
75
+ "yourkey", "redacted", "dummy", "sample", "xxxxxx", "******", "<", ">",
76
+ "${", "{{", "%(", "$(")
77
+ # Whole values that are documentation, as in postgres://user:pass@host
78
+ _PLACEHOLDER_VALUES = {"pass", "password", "passwd", "pwd", "secret", "token", "user"}
79
+ # process.env.API_KEY, settings.SECRET_KEY, self.config.token
80
+ _CODE_PATH = re.compile(r"^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$")
81
+ # MY_OTHER_CONSTANT, get_auth_token: names, not values (no digits)
82
+ _IDENTIFIER = re.compile(r"^(?:[A-Z]+(?:_[A-Z]+)+|[a-z]+(?:_[a-z]+)+)$")
83
+
84
+
85
+ def entropy(s: str) -> float:
86
+ if not s:
87
+ return 0.0
88
+ n = len(s)
89
+ return -sum((c / n) * math.log2(c / n) for c in Counter(s).values())
90
+
91
+
92
+ def redact(secret: str) -> str:
93
+ """Show a short prefix (and suffix for long values); never more than half the secret."""
94
+ n = len(secret)
95
+ if n < 12:
96
+ return secret[:2] + "…"
97
+ return f"{secret[:min(6, n // 4)]}…{secret[-min(4, n // 6):]}"
98
+
99
+
100
+ def fingerprint(secret: str) -> str:
101
+ return hashlib.sha256(secret.encode("utf-8", "replace")).hexdigest()[:12]
102
+
103
+
104
+ def looks_like_placeholder(value: str) -> bool:
105
+ low = value.lower()
106
+ if low in _PLACEHOLDER_VALUES or any(w in low for w in _PLACEHOLDER_WORDS):
107
+ return True
108
+ return bool(_CODE_PATH.match(value) or _IDENTIFIER.match(value))
109
+
110
+
111
+ @dataclass(frozen=True)
112
+ class Finding:
113
+ path: str
114
+ line_no: int
115
+ rule: str
116
+ secret: str
117
+ line_text: str
118
+ commit: str = ""
119
+
120
+ @property
121
+ def redacted(self) -> str:
122
+ return redact(self.secret)
123
+
124
+ @property
125
+ def fingerprint(self) -> str:
126
+ return fingerprint(self.secret)
127
+
128
+ def sort_key(self) -> tuple[str, int, str, str]:
129
+ return (self.path, self.line_no, self.rule, self.commit)
130
+
131
+
132
+ def scan_line(line: str, path: str, line_no: int, *, use_entropy: bool = True,
133
+ commit: str = "") -> list[Finding]:
134
+ if "commitwarden:allow" in line:
135
+ return []
136
+ line = line[:MAX_LINE]
137
+ out: list[Finding] = []
138
+ seen: set[str] = set()
139
+ for rule in RULES:
140
+ if rule.entropy_floor is not None and not use_entropy:
141
+ continue
142
+ for m in rule.pattern.finditer(line):
143
+ if rule.key_filter is not None and not rule.key_filter.search(m.group("key")):
144
+ continue
145
+ secret = (m.group(rule.group) or "").strip().strip("\"'`")
146
+ if not secret or secret in seen:
147
+ continue
148
+ if rule.entropy_floor is not None and entropy(secret) < rule.entropy_floor:
149
+ continue
150
+ if rule.loose and looks_like_placeholder(secret):
151
+ continue
152
+ seen.add(secret)
153
+ out.append(Finding(path, line_no, rule.name, secret[:MAX_SECRET], line.strip(), commit))
154
+ return out
@@ -0,0 +1,394 @@
1
+ Metadata-Version: 2.4
2
+ Name: commitwarden
3
+ Version: 0.1.1
4
+ Summary: Catch secrets before they're committed. Local, zero-config, no network, no telemetry.
5
+ Author: Rrezart Prebreza
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/rrezartprebreza/commitwarden
8
+ Project-URL: Issues, https://github.com/rrezartprebreza/commitwarden/issues
9
+ Project-URL: Changelog, https://github.com/rrezartprebreza/commitwarden/blob/main/CHANGELOG.md
10
+ Keywords: secrets,secret-scanning,security,git,pre-commit,credentials,devsecops
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Classifier: Topic :: Security
24
+ Classifier: Topic :: Software Development :: Version Control :: Git
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=8; extra == "dev"
30
+ Dynamic: license-file
31
+
32
+ # commitwarden
33
+
34
+ [![CI](https://github.com/rrezartprebreza/commitwarden/actions/workflows/ci.yml/badge.svg)](https://github.com/rrezartprebreza/commitwarden/actions/workflows/ci.yml)
35
+ [![PyPI](https://img.shields.io/pypi/v/commitwarden)](https://pypi.org/project/commitwarden/)
36
+ [![Python](https://img.shields.io/badge/python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://github.com/rrezartprebreza/commitwarden/blob/main/pyproject.toml)
37
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)](https://github.com/rrezartprebreza/commitwarden/blob/main/LICENSE)
38
+ [![Dependencies: none](https://img.shields.io/badge/dependencies-none-brightgreen)](https://github.com/rrezartprebreza/commitwarden/blob/main/pyproject.toml)
39
+
40
+ **Catch secrets before they're committed.** A small, local secret scanner for git
41
+ repositories: no config to write, no network calls, no telemetry, pure Python with no
42
+ runtime dependencies.
43
+
44
+ <p align="center">
45
+ <img src="https://raw.githubusercontent.com/rrezartprebreza/commitwarden/main/docs/demo.svg"
46
+ alt="Terminal: git commit is blocked because settings.py contains a GitHub token, an AWS key and a database password; after moving them to environment variables the commit goes through."
47
+ width="820">
48
+ </p>
49
+
50
+ <sub>A real session, generated by <a href="https://github.com/rrezartprebreza/commitwarden/blob/main/scripts/demo_svg.py"><code>scripts/demo_svg.py</code></a>. The keys are fakes.</sub>
51
+
52
+ ## Why
53
+
54
+ Credentials end up in git history all the time, and once pushed they have to be treated as
55
+ leaked: rotating them is the only real fix. Many scanners are large binaries, need
56
+ configuration, or send data to a service, so developers turn them off. commitwarden aims to be
57
+ the one you leave on: it works with zero setup, has no dependencies beyond Python and git,
58
+ and never touches the network.
59
+
60
+ It is a first line of defence on your machine. It does not replace server-side scanning
61
+ (such as GitHub secret scanning) or a secrets manager, and it does not rewrite history.
62
+
63
+ ## Contents
64
+
65
+ - [Install](#install)
66
+ - [Usage](#usage)
67
+ - [Output](#output)
68
+ - [What it detects](#what-it-detects)
69
+ - [What it skips](#what-it-skips)
70
+ - [Suppressing false positives](#suppressing-false-positives)
71
+ - [Use as a pre-commit hook](#use-as-a-pre-commit-hook)
72
+ - [Use in CI](#use-in-ci)
73
+ - [How it works](#how-it-works)
74
+ - [Limitations](#limitations)
75
+ - [Development](#development)
76
+
77
+ ## Install
78
+
79
+ Requires Python 3.10+ and git.
80
+
81
+ ```bash
82
+ pipx install commitwarden
83
+ ```
84
+
85
+ Or into the current environment:
86
+
87
+ ```bash
88
+ pip install commitwarden
89
+ ```
90
+
91
+ ## Usage
92
+
93
+ Run it anywhere inside a git repository. It always scans from the repository root.
94
+
95
+ | Command | Scans |
96
+ |---|---|
97
+ | `commitwarden` or `commitwarden --staged` | The staged version of every added, copied, modified or renamed file: exactly what the next commit will contain. Unstaged edits are ignored. |
98
+ | `commitwarden --all` | Every tracked file plus untracked files that are not `.gitignore`d, as they are on disk. |
99
+ | `commitwarden --history` | Every line ever added in every commit on every branch and tag, including secrets that were later deleted. Each finding names its commit. |
100
+
101
+ ### Options
102
+
103
+ | Option | Effect |
104
+ |---|---|
105
+ | `--json` | Print findings as JSON (see [Output](#output)). |
106
+ | `--baseline PATH` | Ignore findings whose fingerprint is in this file (see [Baseline](#by-fingerprint-baseline)). |
107
+ | `--no-entropy` | Turn off the rules that guess from randomness (generic assignments, bearer tokens); keep the exact provider formats. |
108
+ | `--max-commits N` | With `--history`, only look at the newest `N` commits. |
109
+ | `-q`, `--quiet` | Print nothing; rely on the exit code. |
110
+
111
+ ### Exit codes
112
+
113
+ | Code | Meaning |
114
+ |---|---|
115
+ | `0` | No secrets found. |
116
+ | `1` | At least one secret found. |
117
+ | `2` | Could not scan: not a git repository, git not installed, unreadable or malformed baseline, invalid option. |
118
+
119
+ Because errors exit `2` rather than `0`, a broken setup never looks like a clean scan.
120
+
121
+ ## Output
122
+
123
+ One line per finding on stdout, then a summary on stderr:
124
+
125
+ ```text
126
+ path:line rule redacted-secret [fingerprint] (commit …, with --history only)
127
+ ```
128
+
129
+ ```console
130
+ $ commitwarden --history
131
+ .env:1 generic-assignment x9K…4w [43b6bd32f7d6] (commit 9c513ab67a)
132
+ deploy.py:1 github-pat ghp_x7…R8tY [c3577d3c4374] (commit 7d3e2bc448)
133
+ settings.py:3 db-url-with-password Hun…s9 [1718457635e3] (commit 9c513ab67a)
134
+ settings.py:4 aws-access-key-id AKIAI…PLE [1a5d44a2dca1] (commit 9c513ab67a)
135
+
136
+ 4 secret(s) found.
137
+ ```
138
+
139
+ Here `deploy.py` was deleted in a later commit, so `--all` no longer sees it, but the token
140
+ is still in history and still needs rotating.
141
+
142
+ **Secrets are never printed in full.** Values under 12 characters show only their first 2;
143
+ longer ones show a short prefix and suffix, never more than half the value. The fingerprint
144
+ is the first 12 hex characters of the secret's SHA-256, so the same secret has the same
145
+ fingerprint in every file, commit and machine.
146
+
147
+ With `--json`:
148
+
149
+ ```json
150
+ [
151
+ {
152
+ "path": "settings.py",
153
+ "line": 4,
154
+ "rule": "aws-access-key-id",
155
+ "secret": "AKIAI…PLE",
156
+ "fingerprint": "1a5d44a2dca1"
157
+ }
158
+ ]
159
+ ```
160
+
161
+ `--history` adds a `"commit"` field with the full SHA. Findings are sorted by path, line and
162
+ rule, so the same repository always gives the same output.
163
+
164
+ ## What it detects
165
+
166
+ Exact provider formats:
167
+
168
+ | Rule | Matches |
169
+ |---|---|
170
+ | `aws-access-key-id` | AWS access key IDs (`AKIA…`, `ASIA…`, `ABIA…`, `ACCA…`, `A3T…`) |
171
+ | `aws-secret-access-key` | 40-character values assigned to `aws_secret_access_key` |
172
+ | `github-pat` | GitHub tokens: `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_` |
173
+ | `github-fine-grained-pat` | `github_pat_…` |
174
+ | `gitlab-pat` | `glpat-…` |
175
+ | `slack-token` | `xoxa-`, `xoxb-`, `xoxe-`, `xoxo-`, `xoxp-`, `xoxr-`, `xoxs-` |
176
+ | `slack-webhook` | `https://hooks.slack.com/services/T…/B…/…` |
177
+ | `stripe-key` | Secret and restricted keys: `sk_live_`, `sk_test_`, `rk_live_`, `rk_test_` |
178
+ | `google-api-key` | `AIza…` |
179
+ | `sendgrid-key` | `SG.….…` |
180
+ | `twilio-key` | `SK` followed by 32 hex characters |
181
+ | `npm-token` | `npm_…` |
182
+ | `pypi-token` | `pypi-…` |
183
+ | `openai-key` | `sk-…`, `sk-proj-…`, `sk-svcacct-…`, `sk-admin-…` |
184
+ | `anthropic-key` | `sk-ant-…` |
185
+ | `jwt` | Three base64url segments starting with `eyJ` |
186
+ | `private-key-block` | `-----BEGIN … PRIVATE KEY-----` (RSA, EC, DSA, OpenSSH, PGP, encrypted, PKCS#8) |
187
+
188
+ Heuristic rules, which also check that the value looks real (see [How it works](#how-it-works)):
189
+
190
+ | Rule | Matches |
191
+ |---|---|
192
+ | `db-url-with-password` | The password in any `scheme://user:password@host` URL |
193
+ | `bearer-token` | `Bearer <token>`, for random-looking tokens of 20+ characters |
194
+ | `generic-assignment` | Random-looking values of 12+ characters assigned to a name containing `api_key`, `apikey`, `secret`, `token`, `password`, `passwd`, `pwd`, `auth`, `credential` or `private_key` |
195
+
196
+ The generic rule understands the common assignment styles:
197
+
198
+ ```text
199
+ STRIPE_SECRET_KEY=… .env and shell; any prefix or suffix on the name
200
+ "api_key": "…" JSON
201
+ db_password: … YAML
202
+ apiKey := "…" Go
203
+ 'clientSecret' => '…' PHP
204
+ AUTH_TOKEN=`…` backticks
205
+ ```
206
+
207
+ ## What it skips
208
+
209
+ **Values that are clearly not secrets** (heuristic rules only):
210
+
211
+ - Placeholders: anything containing `example`, `changeme`, `placeholder`, `your_`, `dummy`,
212
+ `sample`, `redacted`, `xxxxxx`, `******`, `<…>`, `${…}`, `{{…}}`, `$(…)` or `%(…)`, and
213
+ bare words like `pass`, `password` or `secret` (as in `postgres://user:pass@host`).
214
+ - References to other values: `process.env.API_KEY`, `settings.SECRET_KEY`,
215
+ `self.config.token`, `MY_OTHER_CONSTANT`.
216
+ - Stripe `pk_` keys, which are public by design.
217
+
218
+ **Files that rarely hold real secrets and are slow or noisy to scan:**
219
+
220
+ - Directories: `.git`, `node_modules`, `vendor`, `dist`, `build`, `target`, `.venv`, `venv`,
221
+ `__pycache__`, `.mypy_cache`, `.pytest_cache`, `.next`, `.terraform`, `Pods`.
222
+ - Lockfiles: `package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `poetry.lock`, `Cargo.lock`,
223
+ `composer.lock`, `Gemfile.lock`, `go.sum`, and any `*.lock`.
224
+ - Minified and binary assets: `.min.js`, `.min.css`, `.map`, images, fonts, archives, video,
225
+ `.wasm`.
226
+ - Any file with a NUL byte in its first 8 KB (treated as binary).
227
+ - Symlinks, which could point outside the repository.
228
+
229
+ Any of these paths can be brought back with a `!` pattern in `.commitwardenignore`.
230
+
231
+ ## Suppressing false positives
232
+
233
+ ### Inline
234
+
235
+ Put `commitwarden:allow` anywhere on the line, usually in a comment:
236
+
237
+ ```python
238
+ TEST_KEY = "sk_test_…" # commitwarden:allow
239
+ ```
240
+
241
+ ### By path: `.commitwardenignore`
242
+
243
+ A file at the repository root, in `.gitignore` syntax. Comments go on their own lines.
244
+
245
+ ```gitignore
246
+ # No slash: matches the file name at any depth
247
+ *.example
248
+ # Contains a slash: relative to the repository root
249
+ fixtures/*
250
+ # Leading slash: root only
251
+ /local-only.env
252
+ # Trailing slash: a directory, at any depth
253
+ testdata/
254
+ # ** matches any number of directories
255
+ **/snapshots/*
256
+ # ! scans a path again
257
+ !fixtures/prod.yml
258
+ ```
259
+
260
+ When several patterns match a path, the last one wins, as in `.gitignore`. A pattern that
261
+ matches a directory covers everything inside it.
262
+
263
+ ### By fingerprint: baseline
264
+
265
+ When adopting commitwarden in an existing repository, record what it finds today and fail
266
+ only on new secrets:
267
+
268
+ ```bash
269
+ commitwarden --all --json > .commitwarden-baseline.json
270
+ git add .commitwarden-baseline.json
271
+ commitwarden --all --baseline .commitwarden-baseline.json # exit 0 until something new appears
272
+ ```
273
+
274
+ The baseline can be the `--json` output as is, or just the fingerprints:
275
+
276
+ ```json
277
+ { "fingerprints": ["1a5d44a2dca1", "43b6bd32f7d6"] }
278
+ ```
279
+
280
+ A baseline holds fingerprints and redacted values only, never the secrets. A missing or
281
+ malformed baseline is an error (exit `2`), never a silent pass. It hides findings; it does not
282
+ make a leaked secret safe, so rotate anything real.
283
+
284
+ ## Use as a pre-commit hook
285
+
286
+ ### With the pre-commit framework
287
+
288
+ Add to `.pre-commit-config.yaml` in your project:
289
+
290
+ ```yaml
291
+ repos:
292
+ - repo: https://github.com/rrezartprebreza/commitwarden
293
+ rev: v0.1.1
294
+ hooks:
295
+ - id: commitwarden
296
+ ```
297
+
298
+ Then:
299
+
300
+ ```bash
301
+ pipx install pre-commit
302
+ pre-commit install
303
+ ```
304
+
305
+ The hook runs `commitwarden --staged`, so it checks exactly what is being committed.
306
+
307
+ ### As a plain git hook
308
+
309
+ ```bash
310
+ printf '#!/bin/sh\nexec commitwarden --staged\n' > .git/hooks/pre-commit
311
+ chmod +x .git/hooks/pre-commit
312
+ ```
313
+
314
+ To commit anyway in an emergency: `git commit --no-verify`.
315
+
316
+ ## Use in CI
317
+
318
+ A GitHub Actions job that fails the build when a secret is pushed:
319
+
320
+ ```yaml
321
+ name: commitwarden
322
+ on: [push, pull_request]
323
+ jobs:
324
+ scan:
325
+ runs-on: ubuntu-latest
326
+ steps:
327
+ - uses: actions/checkout@v4
328
+ with:
329
+ fetch-depth: 0 # full history, for --history
330
+ - uses: actions/setup-python@v5
331
+ with:
332
+ python-version: "3.12"
333
+ - run: pip install commitwarden
334
+ - run: commitwarden --all
335
+ - run: commitwarden --history
336
+ ```
337
+
338
+ ## How it works
339
+
340
+ 1. **List the content** with git (`git diff --cached`, `git ls-files` or `git log -p`), using
341
+ NUL-separated output and fixed options, so unusual file names and personal git settings
342
+ (`diff.noprefix`, `core.quotePath`, colours, external diff tools) don't change the result.
343
+ 2. **Skip** ignored paths and binary content.
344
+ 3. **Scan line by line.** Lines are split on `\n` only, so line numbers match your editor and
345
+ `git blame`. Lines longer than 20,000 characters are scanned up to that point.
346
+ 4. **Match each rule.** For the heuristic rules a candidate must also:
347
+ - have a [Shannon entropy](https://en.wikipedia.org/wiki/Entropy_(information_theory)) of at
348
+ least 3.5 bits per character (generic assignments and bearer tokens), which separates
349
+ random keys like `x9Kq2mZ7pL4w` from repetitive values like `aaaaaaaaaaaa`, and
350
+ - not look like a placeholder or a reference to another value.
351
+
352
+ A value already found by a provider rule is not reported again by a generic rule.
353
+ 5. **Deduplicate:** one finding per secret per file and rule, at its first line (and, in
354
+ history, its earliest commit by sort order).
355
+ 6. **Apply the baseline**, sort, print, and exit `0`, `1` or `2`.
356
+
357
+ ## Limitations
358
+
359
+ - **Line-based.** A secret split across lines is not reassembled. For private keys only the
360
+ `BEGIN` line is matched, which is enough to flag the block.
361
+ - **Heuristics miss things.** The generic rules need a secret-sounding name and a random value
362
+ of 12+ characters, so a short or dictionary-word password, or a key under an unrelated name,
363
+ can slip through. Provider rules are much more reliable.
364
+ - **Text only.** Files are read as UTF-8; secrets inside binary files, archives or images are
365
+ not found.
366
+ - **History covers added lines.** `--history` reports where a secret entered, not every commit
367
+ that still contains it. Merge commits are not diffed separately.
368
+ - **It can't tell whether a key is live.** By design it never calls a provider to check.
369
+
370
+ ## Development
371
+
372
+ ```bash
373
+ git clone https://github.com/rrezartprebreza/commitwarden
374
+ cd commitwarden
375
+ python3 -m venv .venv
376
+ .venv/bin/pip install -e ".[dev]"
377
+ .venv/bin/pytest # 190 tests
378
+ .venv/bin/commitwarden --all # the repository scans itself clean
379
+ ```
380
+
381
+ Tests live in `tests/`:
382
+
383
+ - `test_detectors.py`: every rule, assignment styles, false positives, and redaction for every
384
+ length.
385
+ - `test_allow.py`: default skips and `.commitwardenignore` patterns.
386
+ - `test_cli.py`: all three modes against real temporary git repositories, exit codes,
387
+ baselines, odd file names and personal git config.
388
+
389
+ Fake secrets in the tests are assembled from pieces (`tests/fakes.py`), so no complete token
390
+ appears in the source and the repository passes its own scan.
391
+
392
+ ## License
393
+
394
+ [MIT](https://github.com/rrezartprebreza/commitwarden/blob/main/LICENSE) © 2026 Rrezart Prebreza. See the [changelog](https://github.com/rrezartprebreza/commitwarden/blob/main/CHANGELOG.md) for release notes.
@@ -0,0 +1,10 @@
1
+ commitwarden/__init__.py,sha256=MTMcOQiVnxdYysuchcyspxscuAsI0NcSOERyRXZEaJU,285
2
+ commitwarden/allow.py,sha256=ILU3g_zAfSIubU8V29Y2kTG1FRQaVruGbEvv31jbR_0,2694
3
+ commitwarden/cli.py,sha256=CnDR2dXdF6lI0dUoEGzuoyXPJ_yk654lizMujcifmYY,8636
4
+ commitwarden/detectors.py,sha256=b6o0j2Yny6ln1BPsXAU_TP0tr4tGlA_KA_u21daW_Dc,6410
5
+ commitwarden-0.1.1.dist-info/licenses/LICENSE,sha256=8uOajASV4oUqUtSgxbD9f7qeZVgW-7lptNVx7wwXUCY,1073
6
+ commitwarden-0.1.1.dist-info/METADATA,sha256=RcgnNNBlK9NUsrgxVo93gEQ7CtWN1FfiPow-sUV_ceU,15428
7
+ commitwarden-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
8
+ commitwarden-0.1.1.dist-info/entry_points.txt,sha256=0crpjyl3ACIaIbUuYTj3sPLQMJ-6gm0c-GcYYkHS9Eg,55
9
+ commitwarden-0.1.1.dist-info/top_level.txt,sha256=Y5_i4JZpJguHHrKoPIDc_fKRLElM5oENWFu_NUOa6ec,13
10
+ commitwarden-0.1.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ commitwarden = commitwarden.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rrezart Prebreza
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ commitwarden