leakpulse 0.4.0__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.
leakpulse/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """leakpulse — zero-dependency secret scanner for git worktrees and history."""
2
+
3
+ __version__ = "0.4.0"
4
+ __all__ = ["__version__"]
leakpulse/__main__.py ADDED
@@ -0,0 +1,9 @@
1
+ """Allow `python -m leakpulse`."""
2
+ from __future__ import annotations
3
+
4
+ import sys
5
+
6
+ from .cli import main
7
+
8
+ if __name__ == "__main__":
9
+ sys.exit(main())
leakpulse/cli.py ADDED
@@ -0,0 +1,295 @@
1
+ """Command line interface for leakpulse."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import os
7
+ import sys
8
+ import time
9
+ from pathlib import Path
10
+ from typing import List, Optional, Sequence
11
+
12
+ from . import __version__
13
+ from . import gitutil
14
+ from .exporters import render_html, render_sarif
15
+ from .report import render_text
16
+ from .rules import RULES, SEVERITY_RANK
17
+ from .scanner import (
18
+ IgnoreList,
19
+ ScanOptions,
20
+ dedupe,
21
+ is_default_excluded,
22
+ parse_patch,
23
+ scan_path,
24
+ scan_text,
25
+ )
26
+
27
+ HOOK_MARKER = "# Installed by leakpulse"
28
+ HOOK_TEMPLATE = """#!/bin/sh
29
+ # Installed by leakpulse: scan staged changes before every commit.
30
+ # Remove this file to disable the hook, or reinstall with --force.
31
+ if command -v leakpulse >/dev/null 2>&1; then
32
+ exec leakpulse scan --staged --fail-on high --quiet
33
+ fi
34
+ if [ -n "$LEAKPULSE_SRC" ] && [ -d "$LEAKPULSE_SRC" ]; then
35
+ exec env PYTHONPATH="$LEAKPULSE_SRC" python3 -m leakpulse scan --staged --fail-on high --quiet
36
+ fi
37
+ echo "leakpulse: command not found. Install it (pipx install leakpulse) or set LEAKPULSE_SRC." >&2
38
+ exit 1
39
+ """
40
+
41
+
42
+ def build_parser() -> argparse.ArgumentParser:
43
+ parser = argparse.ArgumentParser(
44
+ prog="leakpulse",
45
+ description="Zero-dependency secret scanner for worktrees, staged changes and git history.",
46
+ )
47
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
48
+ subparsers = parser.add_subparsers(dest="command", required=True)
49
+
50
+ scan = subparsers.add_parser("scan", help="scan files, staged changes or git history")
51
+ scan.add_argument("paths", nargs="*", default=["."], help="files or directories to scan (default: .)")
52
+ scan.add_argument("--staged", action="store_true", help="scan only content staged for commit")
53
+ scan.add_argument(
54
+ "--history",
55
+ type=int,
56
+ default=None,
57
+ metavar="N",
58
+ help="scan the last N commits (default: 50; 0 disables history scanning)",
59
+ )
60
+ scan.add_argument("--json", action="store_true", help="emit machine-readable JSON")
61
+ scan.add_argument(
62
+ "--format",
63
+ choices=["text", "json", "sarif", "html"],
64
+ default=None,
65
+ help="report format: text (default), json, sarif for code scanning, html for audits",
66
+ )
67
+ scan.add_argument("--output", metavar="FILE", default=None, help="write the report to FILE instead of stdout")
68
+ scan.add_argument("--no-color", action="store_true", help="disable ANSI colors")
69
+ scan.add_argument("--no-entropy", action="store_true", help="disable high-entropy detection")
70
+ scan.add_argument("--entropy-threshold", type=float, default=3.6, help="entropy threshold (default: 3.6)")
71
+ scan.add_argument("--min-length", type=int, default=24, help="minimum entropy candidate length (default: 24)")
72
+ scan.add_argument(
73
+ "--fail-on",
74
+ choices=["low", "medium", "high", "never"],
75
+ default="high",
76
+ help="exit non-zero at or above this severity (default: high)",
77
+ )
78
+ scan.add_argument("--exclude", action="append", default=[], metavar="GLOB", help="extra ignore glob (repeatable)")
79
+ scan.add_argument("--all", action="store_true", help="also scan lockfiles and minified assets")
80
+ scan.add_argument("--max-file-bytes", type=int, default=1_000_000, help="skip files larger than this")
81
+ scan.add_argument("--no-ignore-file", action="store_true", help="ignore .leakpulseignore")
82
+ scan.add_argument("--quiet", action="store_true", help="print nothing when clean")
83
+
84
+ rules = subparsers.add_parser("rules", help="list detection rules")
85
+ rules.add_argument("--json", action="store_true", help="emit machine-readable JSON")
86
+
87
+ hook = subparsers.add_parser("install-hook", help="install a pre-commit hook")
88
+ hook.add_argument("--repo", default=".", help="repository path (default: .)")
89
+ hook.add_argument("--force", action="store_true", help="overwrite an existing pre-commit hook")
90
+
91
+ subparsers.add_parser("version", help="print version")
92
+ return parser
93
+
94
+
95
+ def _load_ignore(args: argparse.Namespace, root: Path) -> IgnoreList:
96
+ if args.no_ignore_file:
97
+ return IgnoreList(args.exclude)
98
+ return IgnoreList.load(root / ".leakpulseignore", args.exclude)
99
+
100
+
101
+ def _exit_code(findings, fail_on: str) -> int:
102
+ if fail_on == "never":
103
+ return 0
104
+ threshold = SEVERITY_RANK[fail_on]
105
+ return 1 if any(SEVERITY_RANK[f.severity] >= threshold for f in findings) else 0
106
+
107
+
108
+ def _scan_staged(root: Path, options: ScanOptions, ignore: IgnoreList):
109
+ findings = []
110
+ files_scanned = 0
111
+ for path in gitutil.staged_files(root):
112
+ if ignore.ignored(path):
113
+ continue
114
+ if not options.include_default_excluded and is_default_excluded(path):
115
+ continue
116
+ content = gitutil.staged_content(root, path)
117
+ if content is None:
118
+ continue
119
+ if len(content) > options.max_file_bytes or b"\x00" in content[:8192]:
120
+ continue
121
+ files_scanned += 1
122
+ findings.extend(scan_text(content.decode("utf-8", "replace"), path, options))
123
+ return findings, files_scanned
124
+
125
+
126
+ def _write_report(report: str, output: Optional[str]) -> bool:
127
+ """Emit a rendered report to stdout or to a UTF-8 file."""
128
+ if output is None:
129
+ print(report)
130
+ return True
131
+ path = Path(output)
132
+ try:
133
+ if not path.parent.exists():
134
+ path.parent.mkdir(parents=True, exist_ok=True)
135
+ path.write_text(report if report.endswith("\n") else report + "\n", encoding="utf-8")
136
+ except OSError as exc:
137
+ print(f"leakpulse: cannot write {path}: {exc}", file=sys.stderr)
138
+ return False
139
+ print(f"leakpulse: wrote {path}", file=sys.stderr)
140
+ return True
141
+
142
+
143
+ def run_scan(args: argparse.Namespace) -> int:
144
+ started = time.time()
145
+ report_format = args.format or ("json" if args.json else "text")
146
+ if args.json and args.format and args.format != "json":
147
+ print("leakpulse: --json conflicts with --format " + args.format, file=sys.stderr)
148
+ return 2
149
+ base = Path.cwd()
150
+ options = ScanOptions(
151
+ entropy=not args.no_entropy,
152
+ entropy_threshold=args.entropy_threshold,
153
+ entropy_min_length=args.min_length,
154
+ max_file_bytes=args.max_file_bytes,
155
+ include_default_excluded=args.all,
156
+ )
157
+ root = gitutil.repo_root(base)
158
+ ignore = _load_ignore(args, root or base)
159
+ findings = []
160
+ files_scanned = 0
161
+ commits_scanned = 0
162
+
163
+ if args.staged:
164
+ if root is None:
165
+ print("leakpulse: --staged requires a git repository", file=sys.stderr)
166
+ return 2
167
+ findings, files_scanned = _scan_staged(root, options, ignore)
168
+ history = args.history or 0
169
+ else:
170
+ for target in args.paths:
171
+ if not Path(target).exists():
172
+ print(f"leakpulse: no such file or directory: {target}", file=sys.stderr)
173
+ return 2
174
+ results, count = scan_path(Path(target), options, ignore, root=root)
175
+ findings.extend(results)
176
+ files_scanned += count
177
+ history = 50 if args.history is None else args.history
178
+
179
+ if history > 0 and root is not None:
180
+ for sha in gitutil.rev_list(root, history):
181
+ commits_scanned += 1
182
+ for finding in parse_patch(gitutil.show_patch(root, sha), options, sha[:8]):
183
+ if ignore.ignored(finding.path):
184
+ continue
185
+ findings.append(finding)
186
+
187
+ findings = dedupe(findings)
188
+ elapsed = time.time() - started
189
+ code = _exit_code(findings, args.fail_on)
190
+
191
+ if report_format == "json":
192
+ payload = {
193
+ "tool": "leakpulse",
194
+ "version": __version__,
195
+ "scanned": {"files": files_scanned, "commits": commits_scanned},
196
+ "summary": {
197
+ "total": len(findings),
198
+ "high": sum(1 for f in findings if f.severity == "high"),
199
+ "medium": sum(1 for f in findings if f.severity == "medium"),
200
+ "low": sum(1 for f in findings if f.severity == "low"),
201
+ },
202
+ "findings": [finding.to_dict() for finding in findings],
203
+ "elapsed_seconds": round(elapsed, 3),
204
+ "exit_code": code,
205
+ }
206
+ return code if _write_report(json.dumps(payload, ensure_ascii=False, indent=2), args.output) else 2
207
+
208
+ if report_format == "sarif":
209
+ report = render_sarif(findings, files_scanned, commits_scanned, elapsed, code, __version__)
210
+ return code if _write_report(report, args.output) else 2
211
+
212
+ if report_format == "html":
213
+ report = render_html(findings, files_scanned, commits_scanned, elapsed, code, __version__)
214
+ return code if _write_report(report, args.output) else 2
215
+
216
+ if args.quiet and not findings and args.output is None:
217
+ return code
218
+
219
+ color = (
220
+ args.output is None
221
+ and sys.stdout.isatty()
222
+ and not args.no_color
223
+ and os.environ.get("NO_COLOR") is None
224
+ )
225
+ report = render_text(findings, files_scanned, commits_scanned, elapsed, color=color)
226
+ return code if _write_report(report, args.output) else 2
227
+
228
+
229
+ def run_rules(args: argparse.Namespace) -> int:
230
+ if args.json:
231
+ print(
232
+ json.dumps(
233
+ [
234
+ {"id": rule.id, "severity": rule.severity, "description": rule.description}
235
+ for rule in RULES
236
+ ],
237
+ indent=2,
238
+ )
239
+ )
240
+ return 0
241
+ for rule in RULES:
242
+ print(f"{rule.severity.upper():<7} {rule.id:<28} {rule.description}")
243
+ print(f"\n{len(RULES)} rules (+ high-entropy heuristic)")
244
+ return 0
245
+
246
+
247
+ def run_install_hook(args: argparse.Namespace) -> int:
248
+ repo = Path(args.repo).resolve()
249
+ root = gitutil.repo_root(repo)
250
+ if root is None:
251
+ print(f"leakpulse: {repo} is not inside a git repository", file=sys.stderr)
252
+ return 2
253
+ hooks = gitutil.hooks_dir(root)
254
+ hooks.mkdir(parents=True, exist_ok=True)
255
+ hook_path = hooks / "pre-commit"
256
+ if hook_path.exists():
257
+ existing = hook_path.read_text(encoding="utf-8", errors="replace")
258
+ if HOOK_MARKER not in existing and not args.force:
259
+ print(
260
+ f"leakpulse: {hook_path} already exists and was not created by leakpulse; "
261
+ "use --force to overwrite",
262
+ file=sys.stderr,
263
+ )
264
+ return 2
265
+ hook_path.write_text(HOOK_TEMPLATE, encoding="utf-8")
266
+ hook_path.chmod(0o755)
267
+ print(f"Installed pre-commit hook at {hook_path}")
268
+ print("Set LEAKPULSE_SRC=/path/to/leakpulse/src if leakpulse is not on PATH inside the hook.")
269
+ return 0
270
+
271
+
272
+ def main(argv: Optional[Sequence[str]] = None) -> int:
273
+ parser = build_parser()
274
+ args = parser.parse_args(argv)
275
+ try:
276
+ if args.command == "scan":
277
+ return run_scan(args)
278
+ if args.command == "rules":
279
+ return run_rules(args)
280
+ if args.command == "install-hook":
281
+ return run_install_hook(args)
282
+ if args.command == "version":
283
+ print(__version__)
284
+ return 0
285
+ except gitutil.GitError as exc:
286
+ print(f"leakpulse: {exc}", file=sys.stderr)
287
+ return 2
288
+ except KeyboardInterrupt: # pragma: no cover
289
+ return 130
290
+ parser.error("unknown command")
291
+ return 2
292
+
293
+
294
+ if __name__ == "__main__": # pragma: no cover
295
+ sys.exit(main())
leakpulse/entropy.py ADDED
@@ -0,0 +1,66 @@
1
+ """Shannon entropy helpers used to spot unknown, high-randomness secrets."""
2
+ from __future__ import annotations
3
+
4
+ import math
5
+ import re
6
+ from collections import Counter
7
+ from typing import List, Tuple
8
+
9
+ from .rules import is_placeholder
10
+
11
+ QUOTED_CANDIDATE = re.compile(r"""["']([A-Za-z0-9+/=_\-]{24,})["']""")
12
+ BARE_CANDIDATE = re.compile(r"(?<![A-Za-z0-9+/=_\-])([A-Za-z0-9+/=_\-]{40,})(?![A-Za-z0-9+/=_\-])")
13
+ URL_LIKE = re.compile(r"[a-zA-Z][a-zA-Z0-9+.\-]*://\S+")
14
+ _UUID = re.compile(r"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$")
15
+
16
+
17
+ def shannon_entropy(value: str) -> float:
18
+ """Compute Shannon entropy in bits per character."""
19
+ if not value:
20
+ return 0.0
21
+ counts = Counter(value)
22
+ length = len(value)
23
+ return -sum((count / length) * math.log2(count / length) for count in counts.values())
24
+
25
+
26
+ def looks_random(value: str, threshold: float = 3.6, min_length: int = 24) -> bool:
27
+ """Heuristic: is this string likely to be a generated secret?"""
28
+ if len(value) < min_length:
29
+ return False
30
+ if is_placeholder(value):
31
+ return False
32
+ if _UUID.match(value):
33
+ return False
34
+ if not any(ch.isdigit() for ch in value):
35
+ return False
36
+ if not any(ch.isalpha() for ch in value):
37
+ return False
38
+ # Require some character-class variety; long lowercase identifiers are code.
39
+ has_upper = any(ch.isupper() for ch in value)
40
+ has_lower = any(ch.islower() for ch in value)
41
+ has_symbol = any(ch in "+/=_-" for ch in value)
42
+ if not (has_upper or has_symbol):
43
+ return False
44
+ if not has_lower:
45
+ return False
46
+ return shannon_entropy(value) >= threshold
47
+
48
+
49
+ def candidates(line: str) -> List[Tuple[int, int, str]]:
50
+ """Yield (start, end, value) for strings worth an entropy check."""
51
+ urls = [match.span() for match in URL_LIKE.finditer(line)]
52
+ found: List[Tuple[int, int, str]] = []
53
+ for regex in (QUOTED_CANDIDATE, BARE_CANDIDATE):
54
+ for match in regex.finditer(line):
55
+ start, end = match.start(1), match.end(1)
56
+ if any(start < url_end and end > url_start for url_start, url_end in urls):
57
+ continue
58
+ found.append((start, end, match.group(1)))
59
+ # Longest first so overlapping quoted/bare matches are reported once.
60
+ found.sort(key=lambda item: (item[1] - item[0]), reverse=True)
61
+ deduped: List[Tuple[int, int, str]] = []
62
+ for start, end, value in found:
63
+ if any(start >= s and end <= e for s, e, _ in deduped):
64
+ continue
65
+ deduped.append((start, end, value))
66
+ return deduped
leakpulse/exporters.py ADDED
@@ -0,0 +1,235 @@
1
+ """Machine-readable and shareable reports: SARIF 2.1.0 and standalone HTML.
2
+
3
+ Both renderers are pure functions over scanner results, so they can be tested
4
+ without running a scan. Secrets are never written in full: results only carry
5
+ the masked ``Finding.masked`` value, exactly like the text and JSON reports.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import html
10
+ import json
11
+ from datetime import datetime, timezone
12
+ from typing import Dict, List, Optional
13
+ from urllib.parse import quote
14
+
15
+ from .rules import RULES, SEVERITY_RANK
16
+
17
+ PROJECT_URL = "https://github.com/stackpulse-lab/leakpulse"
18
+ SARIF_SCHEMA = "https://json.schemastore.org/sarif-2.1.0.json"
19
+ SARIF_LEVEL = {"high": "error", "medium": "warning", "low": "note"}
20
+ ENTROPY_RULE = {
21
+ "id": "high-entropy-string",
22
+ "name": "High-entropy string",
23
+ "description": "High-entropy string (possible secret)",
24
+ "severity": "medium",
25
+ }
26
+
27
+
28
+ def _rule_catalog() -> List[Dict[str, str]]:
29
+ """All rules in a stable order: regex rules first, then the heuristic."""
30
+ catalog = [
31
+ {
32
+ "id": rule.id,
33
+ "name": rule.id,
34
+ "description": rule.description,
35
+ "severity": rule.severity,
36
+ }
37
+ for rule in RULES
38
+ ]
39
+ catalog.append(ENTROPY_RULE)
40
+ return catalog
41
+
42
+
43
+ def _counts(findings) -> Dict[str, int]:
44
+ counts = {level: 0 for level in SEVERITY_RANK}
45
+ for finding in findings:
46
+ counts[finding.severity] += 1
47
+ return counts
48
+
49
+
50
+ def _uri(path: str) -> str:
51
+ """Percent-encode a repository-relative path for a SARIF artifact URI."""
52
+ return quote(path.replace("\\", "/"), safe="/")
53
+
54
+
55
+ def render_sarif(
56
+ findings,
57
+ files_scanned: int,
58
+ commits_scanned: int,
59
+ elapsed: float,
60
+ exit_code: int,
61
+ version: str,
62
+ ) -> str:
63
+ catalog = _rule_catalog()
64
+ index_by_id = {rule["id"]: index for index, rule in enumerate(catalog)}
65
+ rules = [
66
+ {
67
+ "id": rule["id"],
68
+ "name": rule["name"],
69
+ "shortDescription": {"text": rule["description"]},
70
+ "defaultConfiguration": {"level": SARIF_LEVEL[rule["severity"]]},
71
+ "helpUri": f"{PROJECT_URL}#rules",
72
+ "properties": {"severity": rule["severity"], "tags": ["security", "secrets"]},
73
+ }
74
+ for rule in catalog
75
+ ]
76
+
77
+ results = []
78
+ for finding in findings:
79
+ message = f"{finding.description} detected ({finding.masked})"
80
+ properties = {"severity": finding.severity}
81
+ if finding.commit:
82
+ properties["commit"] = finding.commit
83
+ results.append(
84
+ {
85
+ "ruleId": finding.rule_id,
86
+ "ruleIndex": index_by_id.get(finding.rule_id, len(catalog) - 1),
87
+ "level": SARIF_LEVEL[finding.severity],
88
+ "message": {"text": message},
89
+ "locations": [
90
+ {
91
+ "physicalLocation": {
92
+ "artifactLocation": {"uri": _uri(finding.path)},
93
+ "region": {"startLine": max(1, finding.line)},
94
+ }
95
+ }
96
+ ],
97
+ "partialFingerprints": {"leakpulse/v1": finding.fingerprint},
98
+ "properties": properties,
99
+ }
100
+ )
101
+
102
+ payload = {
103
+ "$schema": SARIF_SCHEMA,
104
+ "version": "2.1.0",
105
+ "runs": [
106
+ {
107
+ "tool": {
108
+ "driver": {
109
+ "name": "LeakPulse",
110
+ "informationUri": PROJECT_URL,
111
+ "version": version,
112
+ "rules": rules,
113
+ }
114
+ },
115
+ "invocations": [
116
+ {
117
+ "executionSuccessful": True,
118
+ "properties": {
119
+ "filesScanned": files_scanned,
120
+ "commitsScanned": commits_scanned,
121
+ "elapsedSeconds": round(elapsed, 3),
122
+ "exitCode": exit_code,
123
+ },
124
+ }
125
+ ],
126
+ "results": results,
127
+ "properties": {"summary": _counts(findings)},
128
+ }
129
+ ],
130
+ }
131
+ return json.dumps(payload, ensure_ascii=False, indent=2)
132
+
133
+
134
+ HTML_STYLE = """
135
+ :root { color-scheme: light dark; }
136
+ body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
137
+ "Helvetica Neue", Arial, "PingFang SC", "Microsoft YaHei", sans-serif;
138
+ margin: 2rem auto; max-width: 1100px; padding: 0 1rem; line-height: 1.5; }
139
+ h1 { font-size: 1.5rem; margin-bottom: .25rem; }
140
+ .meta { color: #6b7280; font-size: .875rem; margin-bottom: 1.5rem; }
141
+ .cards { display: flex; flex-wrap: wrap; gap: .75rem; margin-bottom: 1.5rem; }
142
+ .card { border: 1px solid #d1d5db; border-radius: 8px; padding: .75rem 1rem; min-width: 7rem; }
143
+ .card .num { font-size: 1.5rem; font-weight: 600; display: block; }
144
+ .high .num { color: #b91c1c; }
145
+ .medium .num { color: #b45309; }
146
+ .low .num { color: #0e7490; }
147
+ table { border-collapse: collapse; width: 100%; font-size: .875rem; }
148
+ th, td { border-bottom: 1px solid #e5e7eb; padding: .5rem; text-align: left; vertical-align: top; }
149
+ th { background: #f9fafb; }
150
+ code { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
151
+ tr.sev-high td:first-child { border-left: 3px solid #b91c1c; }
152
+ tr.sev-medium td:first-child { border-left: 3px solid #b45309; }
153
+ tr.sev-low td:first-child { border-left: 3px solid #0e7490; }
154
+ footer { color: #6b7280; font-size: .8rem; margin-top: 2rem; }
155
+ """
156
+
157
+
158
+ def render_html(
159
+ findings,
160
+ files_scanned: int,
161
+ commits_scanned: int,
162
+ elapsed: float,
163
+ exit_code: int,
164
+ version: str,
165
+ generated_at: Optional[datetime] = None,
166
+ ) -> str:
167
+ moment = generated_at or datetime.now(timezone.utc)
168
+ counts = _counts(findings)
169
+ rows = []
170
+ for finding in findings:
171
+ location = html.escape(finding.location)
172
+ rows.append(
173
+ "<tr class=\"sev-{sev}\">"
174
+ "<td><strong>{sev}</strong></td>"
175
+ "<td><code>{rule}</code></td>"
176
+ "<td><code>{location}</code></td>"
177
+ "<td><code>{masked}</code></td>"
178
+ "<td>{description}</td>"
179
+ "</tr>".format(
180
+ sev=html.escape(finding.severity),
181
+ rule=html.escape(finding.rule_id),
182
+ location=location,
183
+ masked=html.escape(finding.masked),
184
+ description=html.escape(finding.description),
185
+ )
186
+ )
187
+ if rows:
188
+ table = (
189
+ "<table><thead><tr><th>Severity</th><th>Rule</th><th>Location</th>"
190
+ "<th>Match (masked)</th><th>Description</th></tr></thead><tbody>"
191
+ + "".join(rows)
192
+ + "</tbody></table>"
193
+ )
194
+ else:
195
+ table = "<p>No potential secrets found.</p>"
196
+
197
+ scope = f"{files_scanned} file(s)"
198
+ if commits_scanned:
199
+ scope += f", {commits_scanned} commit(s)"
200
+ return """<!DOCTYPE html>
201
+ <html lang="en">
202
+ <head>
203
+ <meta charset="utf-8">
204
+ <meta name="viewport" content="width=device-width, initial-scale=1">
205
+ <title>LeakPulse audit report</title>
206
+ <style>{style}</style>
207
+ </head>
208
+ <body>
209
+ <h1>LeakPulse audit report</h1>
210
+ <p class="meta">LeakPulse {version} &middot; generated {generated} &middot; scanned {scope}
211
+ &middot; {elapsed:.2f}s &middot; exit code {exit_code}</p>
212
+ <div class="cards">
213
+ <div class="card high"><span class="num">{high}</span>high</div>
214
+ <div class="card medium"><span class="num">{medium}</span>medium</div>
215
+ <div class="card low"><span class="num">{low}</span>low</div>
216
+ <div class="card"><span class="num">{total}</span>total</div>
217
+ </div>
218
+ {table}
219
+ <footer>Matches are masked; rotate any credential that this report identifies.
220
+ Generated locally by LeakPulse &mdash; no data was uploaded.</footer>
221
+ </body>
222
+ </html>
223
+ """.format(
224
+ style=HTML_STYLE,
225
+ version=html.escape(version),
226
+ generated=html.escape(moment.strftime("%Y-%m-%d %H:%M:%S UTC")),
227
+ scope=html.escape(scope),
228
+ elapsed=elapsed,
229
+ exit_code=exit_code,
230
+ high=counts["high"],
231
+ medium=counts["medium"],
232
+ low=counts["low"],
233
+ total=len(findings),
234
+ table=table,
235
+ )
leakpulse/gitutil.py ADDED
@@ -0,0 +1,75 @@
1
+ """Thin, testable wrappers around the git CLI (no third-party dependencies)."""
2
+ from __future__ import annotations
3
+
4
+ import subprocess
5
+ from pathlib import Path
6
+ from typing import List, Optional
7
+
8
+
9
+ class GitError(RuntimeError):
10
+ pass
11
+
12
+
13
+ def _run(repo: Path, *args: str, check: bool = True) -> subprocess.CompletedProcess:
14
+ try:
15
+ result = subprocess.run(
16
+ ["git", "-c", "core.quotepath=false", *args],
17
+ cwd=str(repo),
18
+ capture_output=True,
19
+ text=False,
20
+ )
21
+ except FileNotFoundError as exc: # pragma: no cover - git is required for these paths
22
+ raise GitError("git executable not found") from exc
23
+ if check and result.returncode != 0:
24
+ stderr = result.stderr.decode("utf-8", "replace").strip()
25
+ raise GitError(f"git {' '.join(args)} failed: {stderr}")
26
+ return result
27
+
28
+
29
+ def repo_root(path: Path) -> Optional[Path]:
30
+ if not Path(path).exists():
31
+ return None
32
+ result = _run(Path(path), "rev-parse", "--show-toplevel", check=False)
33
+ if result.returncode != 0:
34
+ return None
35
+ root = result.stdout.decode("utf-8", "replace").strip()
36
+ return Path(root) if root else None
37
+
38
+
39
+ def hooks_dir(repo: Path) -> Path:
40
+ result = _run(repo, "rev-parse", "--git-path", "hooks")
41
+ return repo / result.stdout.decode("utf-8", "replace").strip()
42
+
43
+
44
+ def staged_files(repo: Path) -> List[str]:
45
+ result = _run(repo, "diff", "--cached", "--name-only", "--diff-filter=ACMR", "-z", check=False)
46
+ if result.returncode != 0:
47
+ return []
48
+ raw = result.stdout.decode("utf-8", "replace")
49
+ return [item for item in raw.split("\0") if item]
50
+
51
+
52
+ def staged_content(repo: Path, path: str) -> Optional[bytes]:
53
+ result = _run(repo, "show", f":{path}", check=False)
54
+ return result.stdout if result.returncode == 0 else None
55
+
56
+
57
+ def is_repo_dirty(repo: Path) -> bool:
58
+ result = _run(repo, "status", "--porcelain", check=False)
59
+ return bool(result.stdout.strip())
60
+
61
+
62
+ def rev_list(repo: Path, max_commits: int) -> List[str]:
63
+ if max_commits <= 0:
64
+ return []
65
+ result = _run(repo, "rev-list", f"--max-count={max_commits}", "HEAD", check=False)
66
+ if result.returncode != 0:
67
+ return []
68
+ return [line for line in result.stdout.decode("utf-8", "replace").splitlines() if line]
69
+
70
+
71
+ def show_patch(repo: Path, sha: str) -> str:
72
+ result = _run(repo, "show", "--format=", "--no-ext-diff", "--no-color", "--unified=0", sha, check=False)
73
+ if result.returncode != 0:
74
+ return ""
75
+ return result.stdout.decode("utf-8", "replace")