Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-receipts/blob/main/audit/tools/checks.py # aien-receipts Append-only AIEN verification receipts, indexed by repository and exact source commit. Read verdicts, signatures and retained logs before making a claim. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-receipts / audit / tools / checks.py` 687 lines ยท 35530 bytes Raw Blame History 1 #!/usr/bin/env python3 2 """Deterministic audit checks for one repository at one commit. 3 4 Usage: 5 checks.py --repo NAME --out DIR [--fork-base SHA] [--tools DIR] [--worktree DIR] [--only C1,C5] 6 7 The tree is read raw from git objects (loc.materialize), never checked out. 8 Each check writes DIR/.json (normalized, sorted, no timestamps) and the 9 summary DIR/checks.json lists, per check: tool and version, the exact command, 10 status, counts, the sha256 of exactly the bytes written to DIR/.json, and 11 whether a second run on another machine must give the same hash (reproducible) 12 or is a dated snapshot (advisory databases). 13 14 Tools are pinned in tools.lock.json; a tool whose printed version differs from 15 the lock is treated as missing, so a result is never produced by an unpinned tool. 16 17 Status values: 18 PASS tool ran over every target and reported nothing 19 FLAGGED tool ran and reported items; each needs triage (recorded as findings in the stamp) 20 INCOMPLETE tool ran but some targets were not analysed (parse errors, timeouts, one of two 21 scanners missing); the gaps are listed. Never counts as PASS. 22 NOT_RUN tool could not run here (missing, wrong version, crashed); the reason is recorded 23 A FLAGGED check is not a failure by itself: the stamp's findings say what each item was. 24 Files that text checks did not read (binary, larger than TEXT_LIMIT, symlinks, submodules) 25 are listed in checks.json under "not_scanned". 26 """ 27 import argparse, fnmatch, hashlib, ipaddress, json, os, re, shutil, subprocess, sys, tempfile 28 29 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) 30 import loc # noqa: E402 31 32 HERE = os.path.dirname(os.path.abspath(__file__)) 33 TEXT_LIMIT = 2_000_000 # bytes; larger blobs are scanned by gitleaks only 34 CHECKER_VERSION = "aien-audit-checks/3" 35 LOCK_PATH = os.path.join(HERE, "tools.lock.json") 36 37 38 def canonical(obj): 39 return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode() + b"\n" 40 41 42 def run(cmd, **kw): 43 return subprocess.run(cmd, capture_output=True, **kw) 44 45 46 def ver(cmd): 47 try: 48 r = run(cmd, text=True, timeout=120) 49 return ((r.stdout or r.stderr).strip().splitlines() or [""])[0] 50 except Exception as e: # noqa: BLE001 51 return "unavailable: " + type(e).__name__ 52 53 54 def load_lock(path=LOCK_PATH): 55 with open(path, "rb") as fh: 56 data = fh.read() 57 return json.loads(data), hashlib.sha256(data).hexdigest() 58 59 60 class Ctx: 61 def __init__(self, gd, sha, repo, fork_base, tools, root, entries, cats, lock=None): 62 self.gd, self.sha, self.repo, self.fork_base, self.tools = gd, sha, repo, fork_base, tools 63 self.root, self.entries, self.cats = root, entries, cats 64 self.lock = lock if lock is not None else {"tools": {}} 65 self.not_scanned = {} # path -> reason, for files the text checks could not read 66 self.extra_paths = [] 67 self.wt = "" 68 69 def tool(self, name): 70 """Return (path, version, reason). path is None when the tool is missing or not the pinned version.""" 71 p = os.path.join(self.tools, name) 72 p = p if os.path.exists(p) else shutil.which(os.path.basename(name)) 73 if not p: 74 return None, "", f"{name} not installed" 75 pin = self.lock.get("tools", {}).get(name) 76 if not pin: 77 return None, "", f"{name} has no pin in tools.lock.json" 78 v = ver([p, *pin["version_cmd"]]) 79 if not re.search(r"(? TEXT_LIMIT: 87 self.not_scanned[p] = "larger than %d bytes" % TEXT_LIMIT 88 continue 89 with open(full, "rb") as fh: 90 data = fh.read() 91 if b"\0" in data[:8000]: 92 self.not_scanned[p] = "binary (NUL byte in first 8000 bytes)" 93 continue 94 yield p, data.decode("utf-8", "replace") 95 96 def paths(self, categories): 97 return [p for p in sorted(self.cats) if self.cats[p][0] in categories] 98 99 100 def result(check, tool, version, command, items, reproducible=True, note="", status=None, payload=None): 101 """Summary entry plus the exact bytes to write. output_sha256 always covers those bytes.""" 102 norm = canonical(items if payload is None else payload) 103 if status is None: 104 status = "FLAGGED" if items else "PASS" 105 return {"check": check, "tool": tool, "version": version, "command": command, "status": status, 106 "count": len(items) if isinstance(items, list) else None, 107 "output_sha256": hashlib.sha256(norm).hexdigest(), "reproducible": reproducible, "note": note}, norm 108 109 110 def not_run(check, tool, reason, version="", reproducible=True): 111 return result(check, tool, version, "", [], status="NOT_RUN", note=reason, reproducible=reproducible) 112 113 114 # C1: secrets over history ---------------------------------------------------------------------- 115 def c1(ctx): 116 gl, v, why = ctx.tool("gitleaks") 117 if not gl: 118 return not_run("C1-secrets", "gitleaks", why, v) 119 rng = f"{ctx.fork_base}..{ctx.sha}" if ctx.fork_base else ctx.sha 120 with tempfile.TemporaryDirectory() as t: 121 rep = os.path.join(t, "r.json") 122 cmd = [gl, "git", "--no-banner", "--redact", "--exit-code", "0", "--report-format", "json", 123 "--report-path", rep, "--log-opts", rng, ctx.gd] 124 r = run(cmd) 125 if r.returncode != 0 or not os.path.exists(rep): 126 return not_run("C1-secrets", "gitleaks", "gitleaks exit %d: %s" % (r.returncode, r.stderr.decode()[-300:]), v) 127 with open(rep) as fh: 128 raw = json.load(fh) or [] 129 items = sorted({(f["RuleID"], f["File"], f["Commit"], f["StartLine"]) for f in raw}) 130 items = [{"rule": a, "file": b, "commit": c, "line": d} for a, b, c, d in items] 131 cmd_s = f"gitleaks git --no-banner --redact --exit-code 0 --report-format json --log-opts {rng} " 132 return result("C1-secrets", "gitleaks", v, cmd_s, items, 133 note="history reachable from the commit" + (" since the upstream merge-base" if ctx.fork_base else "") 134 + "; secrets redacted by gitleaks; each hit is triaged in findings") 135 136 137 # C2: license consistency ----------------------------------------------------------------------- 138 LICENSE_SIGS = [ 139 ("AGPL-3.0", r"GNU AFFERO GENERAL PUBLIC LICENSE"), 140 ("LGPL", r"GNU LESSER GENERAL PUBLIC LICENSE"), 141 ("GPL", r"GNU GENERAL PUBLIC LICENSE"), 142 ("Apache-2.0", r"Apache License,?\s+Version 2\.0"), 143 ("MPL-2.0", r"Mozilla Public License,? (version|v\.?) ?2\.0"), 144 ("MIT", r"Permission is hereby granted, free of charge"), 145 ("BSD", r"Redistribution and use in source and binary forms"), 146 ("Unlicense", r"This is free and unencumbered software"), 147 ("CC-BY-4.0", r"Creative Commons Attribution 4\.0"), 148 ("CC0-1.0", r"CC0 1\.0 Universal"), 149 ("BSD-2-Clause-Patent", r"BSD-2-Clause-Patent"), 150 ("Community-Spec-1.0", r"Community Specification License 1\.0"), 151 ] 152 # An SPDX expression: ids joined by AND/OR/WITH (either case), optional parens, ending the line or 153 # comment. Prose that merely mentions the tag ("... GPL-2.0-only and remain under") does not match. 154 _SPDX_ID = r"\(*[A-Za-z0-9.+\-]+\)*" 155 SPDX_RE = re.compile(r"SPDX-License-Identifier:\s*(" + _SPDX_ID + r"(?:\s+(?:AND|OR|WITH|and|or|with)\s+" 156 + _SPDX_ID + r")*)\s*(?:\*/|-->|$)", re.M) 157 CARGO_RE = re.compile(r'^\s*license\s*=\s*"([^"]+)"', re.M) 158 LICENSE_FILE_RE = re.compile(r"(?i)^((LICEN[SC]E|COPYING|UNLICENSE)([.-].*)?|.+\.LICEN[SC]E)$") 159 160 161 def ident(text): 162 """Name the licence a licence file grants: an SPDX expression it declares in its first 1 KB wins; 163 otherwise the signature that appears EARLIEST in the text (a GPL text mentions the LGPL further down, 164 a dual-licence file names both). A file that opens with its own versioned licence title before the 165 first known signature (a custom licence wrapping Apache text) is UNRECOGNIZED, not the wrapped licence.""" 166 m = SPDX_RE.search(text[:1000]) 167 if m: 168 return m.group(1).strip() 169 text = re.sub(r"\s+", " ", text) # reflowed licence text (license.rst) still matches its signature 170 hits = [(mm.start(), name) for name, rx in LICENSE_SIGS for mm in [re.search(rx, text, re.I)] if mm] 171 if not hits: 172 return "UNRECOGNIZED" 173 start, name = min(hits) 174 if re.search(r"\bLicen[sc]e,?\s+(v(ersion)?\.?\s*)?\d", text[:start], re.I): 175 return "UNRECOGNIZED" 176 return name 177 178 179 def families(expr): 180 return set(re.findall(r"[A-Za-z0-9.\-+]+", expr)) - {"OR", "AND", "WITH", "or", "and", "with"} 181 182 183 def c2(ctx): 184 # Licence files are read from the audited commit itself, not from the scanned file set: in fork-diff mode 185 # the upstream LICENSE is unchanged, so it is outside the diff but still governs the tree. A licence file 186 # in a subdirectory (adapters/x/LICENSE, om/tka/tailscale.LICENSE) also governs the files below it. 187 root_lic, dir_lic = {}, {} 188 for _mode, typ, _oid, p in loc.tree_entries(ctx.gd, ctx.sha): 189 base = p.rsplit("/", 1)[-1] 190 if typ != "blob" or not LICENSE_FILE_RE.match(base): 191 continue 192 name = ident(loc.git(ctx.gd, "cat-file", "blob", "%s:%s" % (ctx.sha, p)).decode("utf-8", "replace")) 193 if "/" not in p: 194 if not base.lower().endswith(".license"): 195 root_lic[p] = name 196 elif name != "UNRECOGNIZED": 197 dir_lic.setdefault(p.rsplit("/", 1)[0], set()).update(families(name)) 198 spdx, manifests = {}, {} 199 for p, t in ctx.texts(("first_party",)): 200 for m in SPDX_RE.finditer(t[:4000]): 201 spdx.setdefault(m.group(1).strip(), []).append(p) 202 base = os.path.basename(p) 203 if base == "Cargo.toml": 204 for m in CARGO_RE.finditer(t): 205 manifests.setdefault(m.group(1), []).append(p) 206 elif base == "package.json": 207 try: 208 v = json.loads(t).get("license") 209 if isinstance(v, str): 210 manifests.setdefault(v, []).append(p) 211 except ValueError: 212 pass 213 elif base == "pyproject.toml": 214 m = re.search(r'^\s*license\s*=\s*(?:\{\s*text\s*=\s*)?"([^"]+)"', t, re.M) 215 if m: 216 manifests.setdefault(m.group(1), []).append(p) 217 declared = set() 218 for name in root_lic.values(): 219 if name != "UNRECOGNIZED": 220 declared |= families(name) 221 items = [] 222 if not root_lic: 223 items.append({"kind": "no-root-license"}) 224 for name, f in sorted(root_lic.items()): 225 # LICENSE/COPYING itself must be recognized; an extra root file (License-History.txt) only matters 226 # when nothing at the root is recognized. 227 stem = name.rsplit(".", 1)[0].upper() 228 if f == "UNRECOGNIZED" and (stem in ("LICENSE", "LICENCE", "COPYING") or not declared): 229 items.append({"kind": "unrecognized-root-license", "file": name}) 230 231 def governing(path): 232 found = set(declared) 233 parts = path.split("/")[:-1] 234 for i in range(1, len(parts) + 1): 235 found |= dir_lic.get("/".join(parts[:i]), set()) 236 return found 237 238 def compatible(expr, path): 239 toks = families(expr) 240 for d in governing(path): 241 for tk in toks: 242 if tk.upper().startswith(d.upper().split("-")[0]): 243 return True 244 return False 245 246 for expr, ps in sorted(spdx.items()): 247 bad = sorted(p for p in ps if not compatible(expr, p)) 248 if bad: 249 items.append({"kind": "spdx-differs-from-root", "spdx": expr, "files": len(bad), "examples": bad[:5]}) 250 for expr, ps in sorted(manifests.items()): 251 bad = sorted(p for p in ps if not compatible(expr, p)) 252 if bad: 253 items.append({"kind": "manifest-differs-from-root", "license": expr, "files": bad[:10]}) 254 summary = {"root": root_lic, "spdx": {k: len(v) for k, v in sorted(spdx.items())}, 255 "manifests": {k: len(v) for k, v in sorted(manifests.items())}, 256 "nested": {d: sorted(v) for d, v in sorted(dir_lic.items())}} 257 payload = {"items": items, "summary": summary} 258 r, norm = result("C2-license", "checks.py", CHECKER_VERSION, 259 "root and nested LICENSE text signatures vs SPDX headers (first 4 KB) vs Cargo.toml/package.json/pyproject license", 260 items, payload=payload, 261 note="heuristic match by license family; mismatches are decisions for the owner, not proof of violation") 262 r["summary"] = summary 263 return r, norm 264 265 266 # C3: private paths, internal addresses, personal emails --------------------------------------- 267 PRIV_PATTERNS = { 268 "home-path": re.compile(r"/home/[a-z_][a-z0-9_-]{1,31}/"), 269 "mac-user-path": re.compile(r"/Users/[A-Za-z][A-Za-z0-9._-]{0,31}/"), 270 "ipv4": re.compile(r"(?/, /Users//, 100.64.0.0/10 and RFC1918 IPv4, non-noreply emails; " 320 "first_party+generated+evidence text files", items, 321 note="presence is not proof of harm (paths in docs/evidence are often intended); each kind is triaged; " 322 "email and IP values are recorded as sha256: of the matched text") 323 r["counts"] = dict(sorted(counts.items())) 324 return r, norm 325 326 327 # C4: internal relative links in Markdown ------------------------------------------------------ 328 MD_LINK = re.compile(r"\[[^\]]*\]\(\s*]+)>?(?:\s+\"[^\"]*\")?\s*\)") 329 INLINE_CODE = re.compile(r"`[^`]*`") 330 331 332 def c4(ctx): 333 # Targets resolve against every path in the audited commit, not only the scanned set: in fork-diff mode 334 # a link from our file may point at an unchanged upstream file. 335 tracked = {e[3] for e in loc.tree_entries(ctx.gd, ctx.sha)} 336 dirs = set() 337 for p in tracked: 338 parts = p.split("/") 339 for i in range(1, len(parts)): 340 dirs.add("/".join(parts[:i])) 341 items = [] 342 for p, t in ctx.texts(("first_party",)): 343 if not p.lower().endswith((".md", ".markdown")): 344 continue 345 in_code = False 346 for n, line in enumerate(t.split("\n"), 1): 347 if line.lstrip().startswith("```"): 348 in_code = not in_code 349 continue 350 if in_code: 351 continue 352 # inline code spans are not links (`alloc[T](n)` is call syntax); "[`x`](y)" keeps its target 353 for m in MD_LINK.finditer(INLINE_CODE.sub("", line)): 354 tgt = m.group(1) 355 if re.match(r"^[a-z][a-z0-9+.-]*:", tgt, re.I) or tgt.startswith("#") or tgt.startswith("//"): 356 continue 357 path = tgt.split("#", 1)[0].split("?", 1)[0] 358 if not path: 359 continue 360 from urllib.parse import unquote 361 path = unquote(path) 362 if path.startswith("/"): 363 res = path.lstrip("/") 364 else: 365 res = os.path.normpath(os.path.join(os.path.dirname(p), path)).replace(os.sep, "/") 366 res = res.rstrip("/") 367 if res.startswith(".."): 368 items.append({"file": p, "line": n, "target": tgt, "reason": "escapes repository"}) 369 elif res not in tracked and res not in dirs and res != ".": 370 items.append({"file": p, "line": n, "target": tgt, "reason": "not in tree"}) 371 items.sort(key=lambda i: (i["file"], i["line"], i["target"])) 372 return result("C4-internal-links", "checks.py", CHECKER_VERSION, 373 "Markdown relative links resolved against the commit's tree (code fences and inline code skipped)", items, 374 note="external URLs are not checked here (not reproducible)") 375 376 377 # C5: semgrep static analysis ------------------------------------------------------------------- 378 def semgrep_error_type(e): 379 t = e.get("type", "") 380 # semgrep emits either "Timeout" or ["PartialParsing", [locations...]] 381 return str(t[0]) if isinstance(t, list) and t else str(t) 382 383 384 def c5(ctx): 385 sg, v, why = ctx.tool("venv/bin/semgrep") 386 cfg = os.path.join(ctx.tools, "semgrep-config.yaml") 387 if not sg: 388 return not_run("C5-semgrep", "semgrep", why, v) 389 if not os.path.exists(cfg): 390 return not_run("C5-semgrep", "semgrep", "semgrep-config.yaml missing (build it with semgrep_config.py)", v) 391 with open(cfg, "rb") as fh: 392 cfg_sha = hashlib.sha256(fh.read()).hexdigest() 393 want = ctx.lock.get("semgrep_rules", {}).get("config_sha256") 394 if cfg_sha != want: 395 return not_run("C5-semgrep", "semgrep", f"semgrep-config.yaml sha256 {cfg_sha} != tools.lock.json {want}", v) 396 targets = ctx.paths(("first_party",)) 397 if not targets: 398 return result("C5-semgrep", "semgrep", v, "", [], note="no first-party files") 399 with tempfile.TemporaryDirectory() as t: 400 rep = os.path.join(t, "out.json") 401 cmd = [sg, "scan", "--metrics", "off", "--disable-version-check", "--no-git-ignore", "--jobs", "2", 402 "--timeout", "30", "--max-target-bytes", str(TEXT_LIMIT), "--config", cfg, "--json", "--output", rep, 403 "--quiet"] 404 # Scan only first-party files: copy them into a separate tree so vendored code is excluded. 405 scan = os.path.join(t, "scan") 406 for p in targets: 407 dst = os.path.join(scan, p) 408 os.makedirs(os.path.dirname(dst), exist_ok=True) 409 shutil.copyfile(os.path.join(ctx.root, p), dst) 410 r = run(cmd + [scan], cwd=t, env={**os.environ, "SEMGREP_SEND_METRICS": "off"}) 411 if not os.path.exists(rep): 412 return not_run("C5-semgrep", "semgrep", "semgrep exit %d: %s" % (r.returncode, r.stderr.decode()[-300:]), v) 413 try: 414 with open(rep) as fh: 415 out = json.load(fh) 416 except ValueError: 417 return not_run("C5-semgrep", "semgrep", "semgrep exit %d wrote unparsable JSON" % r.returncode, v) 418 items = sorted({(x["check_id"].split(".")[-1], os.path.relpath(x["path"], scan), x["start"]["line"], 419 x["extra"].get("severity", "")) for x in out.get("results", [])}) 420 items = [{"rule": a, "file": b, "line": c, "severity": d} for a, b, c, d in items] 421 errors = sorted({(semgrep_error_type(e), os.path.relpath(e["path"], scan) if e.get("path") else "") 422 for e in out.get("errors", [])}) 423 errors = [{"type": a, "file": b} for a, b in errors] 424 skipped = sorted({(os.path.relpath(s.get("path", scan), scan), str(s.get("reason", ""))) 425 for s in (out.get("paths", {}) or {}).get("skipped", []) or []}) 426 skipped = [{"file": a, "reason": b} for a, b in skipped] 427 status = None 428 note = "pattern-based; hits are triaged. CodeQL is not part of this checker" 429 if errors or skipped or r.returncode not in (0, 1): 430 status = "INCOMPLETE" 431 note += "; %d error(s) and %d skipped target(s) listed in the output, exit %d" % (len(errors), len(skipped), r.returncode) 432 res, norm = result("C5-semgrep", "semgrep", v, 433 "semgrep scan --metrics off --no-git-ignore --jobs 2 --timeout 30 --config semgrep-config.yaml " 434 "(semgrep-rules @ pinned commit, ERROR+WARNING rules for bash/c/python/js/ts/rust/dockerfile/" 435 "github-actions/generic secrets+ci) over first-party files", items, status=status, note=note, 436 payload={"items": items, "errors": errors, "skipped": skipped}) 437 res["errors"] = len(errors) 438 res["skipped_targets"] = len(skipped) 439 res["targets"] = len(targets) 440 res["config_sha256"] = cfg_sha 441 return res, norm 442 443 444 # C6: workflow security --------------------------------------------------------------------------- 445 def c6(ctx): 446 wfs = [p for p in sorted(ctx.cats) if re.match(r"^\.github/workflows/[^/]+\.ya?ml$", p)] 447 if not wfs: 448 r, n = result("C6-workflows", "zizmor+actionlint", "", "", [], note="no workflows in .github/workflows") 449 r["status"] = "PASS" 450 r["workflows"] = 0 451 return r, n 452 items, gaps = [], [] 453 (zz, vz, wz), (al, va, wa) = ctx.tool("venv/bin/zizmor"), ctx.tool("actionlint") 454 wdir = os.path.join(ctx.root, ".github", "workflows") 455 if not zz: 456 gaps.append(wz) 457 else: 458 r = run([zz, "--offline", "--no-progress", "--format", "json", "--min-severity", "low", wdir]) 459 # zizmor: 0 = no findings, 10..14 = findings by severity, anything else = the tool failed 460 try: 461 if r.returncode != 0 and not 10 <= r.returncode <= 14: 462 raise ValueError("exit %d" % r.returncode) 463 for f in json.loads(r.stdout or b"[]"): 464 loc0 = (f.get("locations") or [{}])[0] 465 sym = loc0.get("symbolic", {}) 466 key = sym.get("key", {}) 467 lk = key.get("Local", {}) if isinstance(key, dict) else {} 468 path = lk.get("verbatim_path") or lk.get("given_path") or "" 469 line = (loc0.get("concrete", {}).get("location", {}).get("start_point", {}) or {}).get("row", -1) + 1 470 items.append({"tool": "zizmor", "rule": f.get("ident", ""), "severity": f.get("determinations", {}).get("severity", ""), 471 "file": os.path.relpath(path, ctx.root) if path.startswith("/") else path, "line": line}) 472 except ValueError as e: 473 gaps.append("zizmor failed (%s): %s" % (e, r.stderr.decode("utf-8", "replace")[-200:])) 474 if not al: 475 gaps.append(wa) 476 else: 477 r = run([al, "-format", "{{json .}}", *[os.path.join(ctx.root, w) for w in wfs]], cwd=ctx.root) 478 # actionlint: 0 = clean, 1 = problems found, 2/3 = the tool failed 479 try: 480 if r.returncode not in (0, 1): 481 raise ValueError("exit %d" % r.returncode) 482 for e in json.loads(r.stdout or b"[]"): 483 items.append({"tool": "actionlint", "rule": e.get("kind", ""), "severity": "", 484 "file": os.path.relpath(e.get("filepath", ""), ctx.root), "line": e.get("line", 0)}) 485 except ValueError as e: 486 gaps.append("actionlint failed (%s): %s" % (e, r.stderr.decode("utf-8", "replace")[-200:])) 487 if len(gaps) == 2: 488 return not_run("C6-workflows", "zizmor+actionlint", "; ".join(gaps), f"{vz}; {va}") 489 items = [dict(t) for t in sorted({tuple(sorted(i.items())) for i in items})] 490 items.sort(key=lambda i: (i["tool"], i["file"], i["line"], i["rule"])) 491 res, norm = result("C6-workflows", "zizmor+actionlint", f"{vz}; {va}", 492 "zizmor --offline --min-severity low .github/workflows; actionlint ", items, 493 status="INCOMPLETE" if gaps else None, payload={"items": items, "gaps": gaps}, 494 note="zizmor offline mode: no online audits (e.g. known-vulnerable actions)" 495 + ("; " + "; ".join(gaps) if gaps else "")) 496 res["workflows"] = len(wfs) 497 return res, norm 498 499 500 # C8: claims without a resolvable citation ---------------------------------------------------- 501 CLAIM = re.compile(r"\b(PASS(ED)?|QUALIFIED|VERIFIED|DEPLOYED|PRODUCTION[- ]READY|BATTLE[- ]TESTED|100% )\b") 502 CITE = re.compile(r"(\]\(|https?://|`[^`]*[/.][^`]*`|\b[0-9a-f]{7,40}\b|#\d+|\b[\w./-]+\.(json|log|md|txt|jsonl|sh|om|rs|c|py)\b|NOT_RUN|PROPOSED)") 503 504 505 def c8(ctx): 506 items = [] 507 for p, t in ctx.texts(("first_party",)): 508 if not p.lower().endswith(".md") or p.count("/") > 1: 509 continue 510 in_code = False 511 for n, line in enumerate(t.split("\n"), 1): 512 if line.lstrip().startswith("```"): 513 in_code = not in_code 514 continue 515 if in_code or not CLAIM.search(line): 516 continue 517 if not CITE.search(line): 518 items.append({"file": p, "line": n, "text": line.strip()[:160]}) 519 return result("C8-uncited-claims", "checks.py", CHECKER_VERSION, 520 "top-level and one-deep Markdown lines containing PASS/QUALIFIED/VERIFIED/DEPLOYED/PRODUCTION-READY " 521 "with no link, path, commit sha or issue reference on the same line", items, 522 note="heuristic: a hit means the line itself cites nothing, not that the claim is false") 523 524 525 # C9: crumb structure ----------------------------------------------------------------------------- 526 def c9(ctx): 527 crumbs = [p for p in ctx.cats if os.path.basename(p) == ".crumb"] 528 if not crumbs: 529 return result("C9-crumb", "crumb", "", "", [], status="PASS", note="no .crumb files") 530 pin = ctx.lock.get("crumb", {}) 531 tool = "crumb (%s@%s %s)" % (pin.get("repository", "?"), pin.get("commit", "?"), pin.get("source", "?")) 532 if not ctx.wt: 533 return not_run("C9-crumb", tool, "no worktree given") 534 wt_head = run(["git", "-C", ctx.wt, "rev-parse", "HEAD"]).stdout.decode().strip() 535 if wt_head != ctx.sha or run(["git", "-C", ctx.wt, "status", "--porcelain"]).stdout.strip(): 536 return not_run("C9-crumb", tool, "worktree is not a clean checkout of the audited commit (HEAD %s)" % wt_head[:12]) 537 cr, src = os.path.join(ctx.tools, "crumb-arch"), os.path.join(ctx.tools, "crumb.c") 538 if not (os.path.exists(cr) and os.path.exists(src)): 539 return not_run("C9-crumb", tool, "crumb-arch binary or its crumb.c source missing from the tools directory") 540 with open(src, "rb") as fh: 541 src_sha = hashlib.sha256(fh.read()).hexdigest() 542 if src_sha != pin.get("source_sha256"): 543 return not_run("C9-crumb", tool, f"crumb.c sha256 {src_sha} != tools.lock.json {pin.get('source_sha256')}") 544 r = run([cr, "verify", ctx.wt], cwd=ctx.wt) 545 out = (r.stdout + r.stderr).decode("utf-8", "replace") 546 out = out.replace(ctx.wt, "") 547 items = [] if r.returncode == 0 else [{"exit": r.returncode, "output": out.strip()[-2000:]}] 548 res, norm = result("C9-crumb", tool, "source sha256 " + src_sha, 549 "crumb verify ", items, 550 note="RFC-0003: committed crumb data equals what compile would write") 551 res["crumb_files"] = len(crumbs) 552 return res, norm 553 554 555 # C11: dependency advisories (snapshot) ---------------------------------------------------------- 556 def c11(ctx): 557 osv, v, why = ctx.tool("osv-scanner") 558 if not osv: 559 return not_run("C11-dep-advisories", "osv-scanner", why, v, reproducible=False) 560 with tempfile.TemporaryDirectory() as t: 561 scan = os.path.join(t, "scan") 562 n = 0 563 for p in ctx.paths(("first_party", "generated")): 564 if os.path.basename(p) in LOCKFILES: 565 dst = os.path.join(scan, p) 566 os.makedirs(os.path.dirname(dst), exist_ok=True) 567 shutil.copyfile(os.path.join(ctx.root, p), dst) 568 n += 1 569 if not n: 570 return result("C11-dep-advisories", "osv-scanner", v, "", [], reproducible=False, note="no lockfiles") 571 r = run([osv, "scan", "source", "-r", "--format", "json", scan]) 572 # osv-scanner: 0 = no vulnerabilities, 1 = vulnerabilities found, 128 = no packages found, other = error 573 if r.returncode not in (0, 1): 574 why = "no packages parsed from %d lockfile(s)" % n if r.returncode == 128 else "osv-scanner failed" 575 return not_run("C11-dep-advisories", "osv-scanner", 576 "%s (exit %d): %s" % (why, r.returncode, r.stderr.decode("utf-8", "replace")[-300:]), v, 577 reproducible=False) 578 try: 579 out = json.loads(r.stdout or b"") 580 except ValueError: 581 return not_run("C11-dep-advisories", "osv-scanner", "exit %d with unparsable JSON" % r.returncode, v, 582 reproducible=False) 583 items = [] 584 for res in out.get("results", []) or []: 585 src = os.path.relpath(res["source"]["path"], scan) 586 for pk in res.get("packages", []): 587 for vv in pk.get("vulnerabilities", []): 588 items.append({"lockfile": src, "package": pk["package"]["name"], "version": pk["package"].get("version", ""), 589 "id": vv["id"]}) 590 items = sorted(items, key=lambda i: (i["lockfile"], i["package"], i["version"], i["id"])) 591 if r.returncode == 1 and not items: 592 return not_run("C11-dep-advisories", "osv-scanner", "exit 1 (vulnerabilities) but none parsed from JSON", v, 593 reproducible=False) 594 res, norm = result("C11-dep-advisories", "osv-scanner", v, 595 "osv-scanner scan source -r --format json ", items, reproducible=False, 596 note=f"{n} lockfile(s); OSV database queried online at run time, so results are a dated snapshot") 597 res["lockfiles"] = n 598 return res, norm 599 600 601 LOCKFILES = ("Cargo.lock", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "uv.lock", "Pipfile.lock", 602 "go.sum", "requirements.txt", "Gemfile.lock", "composer.lock") 603 604 605 CHECKS = {"C1": c1, "C2": c2, "C3": c3, "C4": c4, "C5": c5, "C6": c6, "C8": c8, "C9": c9, "C11": c11} 606 CHECK_NAMES = {"C1": "C1-secrets", "C2": "C2-license", "C3": "C3-privacy", "C4": "C4-internal-links", "C5": "C5-semgrep", 607 "C6": "C6-workflows", "C8": "C8-uncited-claims", "C9": "C9-crumb", "C11": "C11-dep-advisories"} 608 609 610 def checker_sha256(): 611 h = hashlib.sha256() 612 for name in ("checks.py", "loc.py"): 613 with open(os.path.join(HERE, name), "rb") as fh: 614 h.update(name.encode() + b"\0" + hashlib.sha256(fh.read()).hexdigest().encode() + b"\n") 615 return h.hexdigest() 616 617 618 def run_all(gd, sha, repo, out, fork_base="", tools=HERE, worktree="", only="", lock_path=LOCK_PATH): 619 sha = loc.git(gd, "rev-parse", sha + "^{commit}").decode().strip() 620 if fork_base: 621 fork_base = loc.git(gd, "rev-parse", fork_base + "^{commit}").decode().strip() 622 lock, lock_sha = load_lock(lock_path) 623 extra = [] 624 cj = os.path.join(HERE, "classify.json") 625 if os.path.exists(cj): 626 with open(cj) as fh: 627 extra = json.load(fh).get(repo, []) 628 entries, not_scanned = [], {} 629 for mode, typ, oid, path in loc.tree_entries(gd, sha): 630 if typ == "blob" and mode != "120000": 631 entries.append((mode, typ, oid, path)) 632 else: 633 not_scanned[path] = "submodule (gitlink)" if typ == "commit" else "symlink" 634 if fork_base: 635 diff = loc.git(gd, "diff", "--no-renames", "-z", "--name-only", "--diff-filter=AM", fork_base, sha).split(b"\0") 636 keep = {d.decode("utf-8", "surrogateescape") for d in diff if d} 637 entries = [e for e in entries if e[3] in keep] 638 not_scanned = {p: r for p, r in not_scanned.items() if p in keep} 639 os.makedirs(out, exist_ok=True) 640 at = loc.attrs(gd, sha, [e[3] for e in entries]) 641 with tempfile.TemporaryDirectory(prefix="aien-checks-") as root: 642 heads = loc.materialize(gd, entries, root) 643 cats = {p: loc.classify(p, heads[p][0], at.get(p, set()), extra) for p in heads} 644 ctx = Ctx(gd, sha, repo, fork_base, tools, root, entries, cats, lock) 645 ctx.extra_paths = list(not_scanned) 646 ctx.wt = worktree 647 summary = [] 648 for cid, fn in CHECKS.items(): 649 if only and cid not in only.split(","): 650 continue 651 try: 652 r, norm = fn(ctx) 653 except Exception as e: # noqa: BLE001 - a crashed check is NOT_RUN, never a silent gap 654 r, norm = not_run(CHECK_NAMES[cid], "checks.py", "checker crashed: %s: %s" % (type(e).__name__, str(e)[:300])) 655 with open(os.path.join(out, r["check"] + ".json"), "wb") as fh: 656 fh.write(norm) 657 summary.append(r) 658 print(f"{repo} {r['check']} {r['status']} {r['count']}", file=sys.stderr) 659 not_scanned.update(ctx.not_scanned) 660 doc = {"schema": "aien-audit-checks/2", "repository": repo, "commit": sha, 661 "mode": "fork-diff" if fork_base else "full-tree", "fork_base": fork_base or None, 662 "checker": {"version": CHECKER_VERSION, "sha256": checker_sha256()}, "tools_lock_sha256": lock_sha, 663 "files": len(entries), "checks": summary, 664 "not_scanned": [{"path": p, "reason": not_scanned[p]} for p in sorted(not_scanned)]} 665 data = canonical(doc) 666 with open(os.path.join(out, "checks.json"), "wb") as fh: 667 fh.write(data) 668 return doc 669 670 671 def main(): 672 ap = argparse.ArgumentParser() 673 ap.add_argument("gitdir") 674 ap.add_argument("sha") 675 ap.add_argument("--repo", required=True) 676 ap.add_argument("--out", required=True) 677 ap.add_argument("--fork-base", default="") 678 ap.add_argument("--tools", default=os.environ.get("AUDIT_TOOLS", HERE)) 679 ap.add_argument("--worktree", default="", help="checkout at for tools that need a work tree (crumb)") 680 ap.add_argument("--only", default="") 681 ap.add_argument("--lock", default=LOCK_PATH) 682 a = ap.parse_args() 683 run_all(a.gitdir, a.sha, a.repo, a.out, a.fork_base, a.tools, a.worktree, a.only, a.lock) 684 685 686 if __name__ == "__main__": 687 main()