#!/usr/bin/env python3 """Check every tracked text file against an exact, reasoned reference inventory.""" import argparse import collections import hashlib import json from pathlib import Path import re import subprocess import sys PATTERN = re.compile(r"node|npm|\.mjs|paseo|equipo-runner|trial", re.I) INVENTORY = "scripts/runner-reference-allowlist.json" def scan(root, raw=False): names = subprocess.check_output( ["git", "-C", str(root), "ls-files", "-z", "--cached"] ).decode().split("\0") deleted = set(subprocess.check_output( ["git", "-C", str(root), "ls-files", "-z", "--deleted"] ).decode().split("\0")) path = root / INVENTORY entries = json.loads(path.read_text()) if path.exists() else [] if not isinstance(entries, list): raise ValueError("inventory must be a list of exact matches") allowed = {} for e in entries: if (set(e) != {"path", "line_sha256", "match", "count", "reason"} or not re.fullmatch("[a-f0-9]{64}", e["line_sha256"]) or not PATTERN.fullmatch(e["match"]) or not isinstance(e["count"], int) or e["count"] <= 0 or not isinstance(e["reason"], str) or len(e["reason"].strip()) < 12 or e["path"] == INVENTORY or e["path"] not in names): raise ValueError("invalid or blanket allowance: " + repr(e)) key = (e["path"], e["line_sha256"], e["match"]) if key in allowed: raise ValueError("duplicate allowance: " + repr(key)) allowed[key] = e seen = collections.Counter() failures = [] files = 0 for name in sorted(set(names) - {""}): if name == INVENTORY: # This data file is parsed and fully validated above. It cannot # contain executable code, wildcard exemptions or arbitrary keys. continue file = root / name if not file.exists(): if name not in deleted: failures.append("missing tracked file: " + name) continue data = file.read_bytes() if b"\0" in data: continue files += 1 for number, line in enumerate(data.decode("utf-8", errors="replace").splitlines(), 1): digest = hashlib.sha256(line.encode()).hexdigest() for match in PATTERN.finditer(line): token = match.group() key = (name, digest, token) seen[key] += 1 entry = allowed.get(key) label = entry["reason"] if entry else "UNCLASSIFIED" if raw: print(f"{name}:{number}:{match.start()+1}: {token}: {label}: {line}") if not entry: failures.append(f"{name}:{number}:{match.start()+1}: unclassified {token}") for key, entry in allowed.items(): if seen[key] != entry["count"]: failures.append("stale allowance: " + repr(key)) for failure in failures: print(failure, file=sys.stderr) print(f"reference scan: {files} text files, {sum(seen.values())} matches, {len(failures)} failures") return bool(failures) def main(): parser = argparse.ArgumentParser() parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent) parser.add_argument("--raw", action="store_true") args = parser.parse_args() try: return scan(args.root.resolve(), args.raw) except (OSError, ValueError, subprocess.CalledProcessError) as error: print(str(error), file=sys.stderr) return 1 if __name__ == "__main__": sys.exit(main())