Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : QYVORA7# File : security/audit/runners/gitleaks.py8# Module : Security9# Repository : https://git.spboucher.ai/qyvora10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Gitleaks runner: secrets in the working tree and in the full Git history.4243Three steps, all local (Gitleaks makes no network request):44 1. canary: a published BIP-32 test key is piped to `gitleaks stdin` with our configuration; the scan45 must report it, which proves the rules are loaded and firing before a clean result is trusted;46 2. `gitleaks dir .` — every file of the working tree, tracked or not (generated directories excluded47 by the allowlist of security/policies/gitleaks.toml);48 3. `gitleaks git . --log-opts=--all` — the patch of every commit reachable from any reference.4950Any hit is a critical finding (a secret in the repository), reported with the secret redacted.5152Standalone: python3 security/audit/runners/gitleaks.py53"""5455from __future__ import annotations5657import json58import re59import sys60from pathlib import Path6162sys.path.insert(0, str(Path(__file__).resolve().parents[1]))63from lib.common import (FAILED, POLICIES, REPO, RUN, Context, apply_triage, finding, load_json, # noqa: E40264 not_run, run_cmd, tool_pins, tool_result, which)6566CONFIG = POLICIES / "gitleaks.toml"67# BIP-32 test vector 1, master extended private key (public knowledge): used only to prove detection.68CANARY = ('let k = "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGt'69 'RBeJgk33yuGBxrMPHi"\n')70COVERAGE = (71 "Gitleaks default rule set (API keys, tokens, private-key blocks, generic high-entropy assignments) plus "72 "one QYVORA rule for BIP-32 extended private keys, over the working tree and over the patches of every "73 "commit reachable from any reference. Pattern and entropy based: it does not recognise a BIP-39 mnemonic "74 "written as plain words, a raw 32-byte hex key without a telling name, or a secret inside a compressed "75 "or binary file. The allowlist is limited to published test-vector files, each entry justified in "76 "security/policies/gitleaks.toml."77)787980def _scan(exe: str, args: list[str], raw: Path) -> tuple[int, list, str, float]:81 if raw.exists():82 raw.unlink()83 cmd = [exe] + args + ["--config", str(CONFIG), "--report-format", "json", "--report-path", str(raw),84 "--redact=80", "--no-banner", "--no-color", "--exit-code", "0"]85 code, out, err, secs = run_cmd(cmd, timeout=1800)86 return code, (load_json(raw, None) if raw.exists() else None), out + err, secs878889def run(ctx: Context) -> dict:90 exe = which("gitleaks")91 if not exe:92 return not_run("gitleaks", "secrets", "gitleaks is not installed (run security/audit/install-tools.sh)", COVERAGE)93 _, out, _, _ = run_cmd([exe, "version"])94 version = out.strip()95 pin = (tool_pins().get("tools", {}).get("gitleaks", {}) or {}).get("version", "")96 records, findings, total = [], [], 0.09798 # 1. canary99 code, _, err, secs = run_cmd([exe, "stdin", "--config", str(CONFIG), "--no-banner", "--no-color", "--redact",100 "--exit-code", "3"], stdin=CANARY, timeout=120)101 total += secs102 canary_ok = code == 3103 records.append({"area": "secrets", "name": "gitleaks canary (published BIP-32 test key on stdin must be detected)",104 "algorithm": "", "parameter_set": "", "cases": 1, "passed": int(canary_ok),105 "failed": int(not canary_ok), "skipped": 0, "note": ""})106 if not canary_ok:107 return tool_result(tool="gitleaks", category="secrets", status=FAILED, version=version, coverage=COVERAGE,108 reason=f"canary not detected (exit {code}): the configuration is not effective. {err[-300:]}",109 duration_s=total, tests=records)110111 # 2. working tree112 code_d, leaks_d, log_d, secs = _scan(exe, ["dir", "."], ctx.raw_path("gitleaks-dir.json"))113 total += secs114 # 3. history115 code_g, leaks_g, log_g, secs = _scan(exe, ["git", ".", "--log-opts=--all"], ctx.raw_path("gitleaks-history.json"))116 total += secs117 if leaks_d is None or leaks_g is None or code_d != 0 or code_g != 0:118 return tool_result(tool="gitleaks", category="secrets", status=FAILED, version=version, coverage=COVERAGE,119 reason=f"gitleaks failed (dir exit {code_d}, git exit {code_g}): {(log_d + log_g)[-400:]}",120 duration_s=total, tests=records)121122 m = re.search(r"(\d+) commits scanned", log_g)123 commits_scanned = int(m.group(1)) if m else None124 _, all_count, _, _ = run_cmd(["git", "rev-list", "--all", "--count"])125 _, nomerge_count, _, _ = run_cmd(["git", "rev-list", "--all", "--no-merges", "--count"])126 md = re.search(r"scanned ~(\d+) bytes", log_d)127128 seen = set()129 for scope, leaks in (("working tree", leaks_d), ("history", leaks_g)):130 for leak in leaks:131 key = (leak.get("RuleID"), leak.get("File"), leak.get("Secret"), leak.get("Commit", ""))132 if key in seen:133 continue134 seen.add(key)135 where = f"{leak.get('File')}:{leak.get('StartLine')}"136 commit = leak.get("Commit", "")137 findings.append(finding(138 title=f"Secret detected ({leak.get('RuleID')}) in {scope}: {leak.get('File')}",139 severity="critical", location=where, tool="gitleaks", rule=str(leak.get("RuleID")),140 description=(f"Gitleaks rule {leak.get('RuleID')} matched in the {scope}"141 + (f", commit {commit[:12]} ({leak.get('Date', '')})" if commit else "")142 + ". The value is redacted in this report."),143 recommendation=("Revoke the secret, remove it from the tree; a secret in history stays exposed and must "144 "be considered compromised. If it is a published test vector, add a justified allowlist "145 "entry to security/policies/gitleaks.toml."),146 cwe="CWE-798", masvs="MASVS-STORAGE-1", area="supply-chain",147 cvss_vector="CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N", cvss_score=7.5,148 evidence=f"{leak.get('RuleID')}|{leak.get('File')}|{commit}|{leak.get('Fingerprint', '')}"))149 findings = apply_triage(findings)150151 records.append({"area": "secrets", "name": "gitleaks working tree", "algorithm": "", "parameter_set": "",152 "cases": 1, "passed": int(not leaks_d), "failed": int(bool(leaks_d)), "skipped": 0,153 "note": f"{len(leaks_d)} hit(s); ~{md.group(1) if md else '?'} bytes scanned"})154 records.append({"area": "secrets", "name": "gitleaks full history (--all)", "algorithm": "", "parameter_set": "",155 "cases": commits_scanned or 0, "passed": (commits_scanned or 0) if not leaks_g else 0,156 "failed": len({x.get('Commit') for x in leaks_g}), "skipped": 0,157 "note": f"{len(leaks_g)} hit(s) in {commits_scanned} commit patches"})158 allow = len(re.findall(r"^\[\[allowlists\]\]", CONFIG.read_text(), flags=re.M))159 metrics = {160 "working_tree_hits": len(leaks_d), "history_hits": len(leaks_g),161 "bytes_scanned_working_tree": int(md.group(1)) if md else None,162 "commits_scanned": commits_scanned,163 "commits_reachable_all_refs": int(all_count.strip() or 0),164 "commits_reachable_non_merge": int(nomerge_count.strip() or 0),165 "note_commits": "Gitleaks scans the patch of each non-merge commit; merge commits carry no patch of their own.",166 "allowlist_entries": allow, "canary_detected": canary_ok,167 "pinned_version": pin, "version_matches_pin": version == pin,168 }169 return tool_result(170 tool="gitleaks", category="secrets", status=RUN, version=version, duration_s=total, coverage=COVERAGE,171 command=("gitleaks dir . --config security/policies/gitleaks.toml --redact=80 ; "172 "gitleaks git . --log-opts=--all --config security/policies/gitleaks.toml --redact=80"),173 metrics=metrics, tests=records, findings=findings,174 artifacts=["security/reports/raw/gitleaks-dir.json", "security/reports/raw/gitleaks-history.json"])175176177if __name__ == "__main__":178 print(json.dumps(run(Context("full" if "--full" in sys.argv else "quick")), indent=2))179