oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1#!/usr/bin/env python3
2"""Check every tracked text file against an exact, reasoned reference inventory."""
3import argparse
4import collections
5import hashlib
6import json
7from pathlib import Path
8import re
9import subprocess
10import sys
11
12PATTERN = re.compile(r"node|npm|\.mjs|paseo|equipo-runner|trial", re.I)
13INVENTORY = "scripts/runner-reference-allowlist.json"
14
15
16def scan(root, raw=False):
17 names = subprocess.check_output(
18 ["git", "-C", str(root), "ls-files", "-z", "--cached"]
19 ).decode().split("\0")
20 deleted = set(subprocess.check_output(
21 ["git", "-C", str(root), "ls-files", "-z", "--deleted"]
22 ).decode().split("\0"))
23 path = root / INVENTORY
24 entries = json.loads(path.read_text()) if path.exists() else []
25 if not isinstance(entries, list):
26 raise ValueError("inventory must be a list of exact matches")
27 allowed = {}
28 for e in entries:
29 if (set(e) != {"path", "line_sha256", "match", "count", "reason"}
30 or not re.fullmatch("[a-f0-9]{64}", e["line_sha256"])
31 or not PATTERN.fullmatch(e["match"])
32 or not isinstance(e["count"], int) or e["count"] <= 0
33 or not isinstance(e["reason"], str) or len(e["reason"].strip()) < 12
34 or e["path"] == INVENTORY or e["path"] not in names):
35 raise ValueError("invalid or blanket allowance: " + repr(e))
36 key = (e["path"], e["line_sha256"], e["match"])
37 if key in allowed:
38 raise ValueError("duplicate allowance: " + repr(key))
39 allowed[key] = e
40 seen = collections.Counter()
41 failures = []
42 files = 0
43 for name in sorted(set(names) - {""}):
44 if name == INVENTORY:
45 # This data file is parsed and fully validated above. It cannot
46 # contain executable code, wildcard exemptions or arbitrary keys.
47 continue
48 file = root / name
49 if not file.exists():
50 if name not in deleted:
51 failures.append("missing tracked file: " + name)
52 continue
53 data = file.read_bytes()
54 if b"\0" in data:
55 continue
56 files += 1
57 for number, line in enumerate(data.decode("utf-8", errors="replace").splitlines(), 1):
58 digest = hashlib.sha256(line.encode()).hexdigest()
59 for match in PATTERN.finditer(line):
60 token = match.group()
61 key = (name, digest, token)
62 seen[key] += 1
63 entry = allowed.get(key)
64 label = entry["reason"] if entry else "UNCLASSIFIED"
65 if raw:
66 print(f"{name}:{number}:{match.start()+1}: {token}: {label}: {line}")
67 if not entry:
68 failures.append(f"{name}:{number}:{match.start()+1}: unclassified {token}")
69 for key, entry in allowed.items():
70 if seen[key] != entry["count"]:
71 failures.append("stale allowance: " + repr(key))
72 for failure in failures:
73 print(failure, file=sys.stderr)
74 print(f"reference scan: {files} text files, {sum(seen.values())} matches, {len(failures)} failures")
75 return bool(failures)
76
77
78def main():
79 parser = argparse.ArgumentParser()
80 parser.add_argument("--root", type=Path, default=Path(__file__).resolve().parent.parent)
81 parser.add_argument("--raw", action="store_true")
82 args = parser.parse_args()
83 try:
84 return scan(args.root.resolve(), args.raw)
85 except (OSError, ValueError, subprocess.CalledProcessError) as error:
86 print(str(error), file=sys.stderr)
87 return 1
88
89
90if __name__ == "__main__":
91 sys.exit(main())
92