File size: 2,738 Bytes
0109502 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | from __future__ import annotations
import json, os, shutil, subprocess, tempfile
from pathlib import Path
def _truthy(value: str | None) -> bool:
return str(value).strip().lower() in ("1", "true", "yes", "on")
def gitleaks_available() -> bool:
return shutil.which("gitleaks") is not None
def missing_gitleaks_allowed() -> bool:
return _truthy(os.getenv("ALLOW_MISSING_GITLEAKS", "0"))
def ensure_secret_scanner_ready() -> None:
"""Fail-closed startup check. Call this once before processing any records.
If Gitleaks is not on PATH and ALLOW_MISSING_GITLEAKS is not set to a truthy
value, this raises immediately so a run cannot silently process records
without secret scanning coverage.
"""
if gitleaks_available():
return
if missing_gitleaks_allowed():
return
raise RuntimeError(
"Gitleaks was not found on PATH and ALLOW_MISSING_GITLEAKS is not set. "
"Install Gitleaks (https://github.com/gitleaks/gitleaks) and ensure "
"`gitleaks` is on PATH before running the pipeline. For local, "
"non-production development only, you may set ALLOW_MISSING_GITLEAKS=1 "
"to explicitly opt out of secret scanning; every record processed under "
"that override is marked with a warning in its metadata."
)
def scan_code(code: str) -> dict:
g = shutil.which("gitleaks")
if not g:
if missing_gitleaks_allowed():
return {
"passed": True,
"tool": "unavailable",
"findings": [],
"warning": "gitleaks_not_installed_override_allowed",
}
# Defense in depth: even if ensure_secret_scanner_ready() was skipped
# or Gitleaks disappeared mid-run, never silently pass records through.
raise RuntimeError(
"Gitleaks is not installed and ALLOW_MISSING_GITLEAKS is not set to 1. "
"Refusing to pass a record through without a secret scan (fail-closed)."
)
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "x.py"
out = Path(d) / "r.json"
p.write_text(code, encoding="utf-8")
x = subprocess.run(
[g, "detect", "--no-git", "--source", str(p), "--report-format", "json",
"--report-path", str(out), "--redact", "--exit-code", "1"],
capture_output=True, text=True, timeout=20,
)
fs = []
if out.exists():
try:
fs = [{"rule": a.get("RuleID"), "line": a.get("StartLine")} for a in json.loads(out.read_text())]
except Exception:
pass
return {"passed": x.returncode == 0, "tool": "gitleaks", "findings": fs, "warning": None}
|