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
aien-receipts / audit / tools / semgrep_config.py
| 1 | #!/usr/bin/env python3 |
| 2 | """Build semgrep-config.yaml from a semgrep-rules checkout pinned in tools.lock.json. |
| 3 | |
| 4 | Usage: semgrep_config.py <semgrep-rules-checkout> <out.yaml> |
| 5 | |
| 6 | Takes every rule file under the locked directories (test files excluded), keeps |
| 7 | rules whose severity is in the locked list, and writes one YAML document with |
| 8 | PyYAML's safe_dump(sort_keys=True). Exits 1 unless the checkout is at the locked |
| 9 | commit, PyYAML is the locked version and the output sha256 equals config_sha256. |
| 10 | """ |
| 11 | import glob, hashlib, json, os, subprocess, sys |
| 12 | |
| 13 | import yaml |
| 14 | |
| 15 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 16 | |
| 17 | |
| 18 | def build(root, lock): |
| 19 | sr = lock["semgrep_rules"] |
| 20 | rules = [] |
| 21 | for d in sr["directories"]: |
| 22 | for p in sorted(glob.glob(os.path.join(root, d, "**", "*.yaml"), recursive=True)): |
| 23 | if p.endswith(".test.yaml") or "/tests/" in p: |
| 24 | continue |
| 25 | try: |
| 26 | with open(p) as fh: |
| 27 | doc = yaml.safe_load(fh) |
| 28 | except yaml.YAMLError: |
| 29 | continue |
| 30 | if not isinstance(doc, dict) or "rules" not in doc: |
| 31 | continue |
| 32 | rules += [r for r in doc["rules"] if r.get("severity") in sr["severities"]] |
| 33 | return yaml.safe_dump({"rules": rules}, sort_keys=True).encode() |
| 34 | |
| 35 | |
| 36 | def main(): |
| 37 | if len(sys.argv) != 3: |
| 38 | sys.exit(__doc__) |
| 39 | root, out = sys.argv[1], sys.argv[2] |
| 40 | with open(os.path.join(HERE, "tools.lock.json")) as fh: |
| 41 | lock = json.load(fh) |
| 42 | sr = lock["semgrep_rules"] |
| 43 | head = subprocess.run(["git", "-C", root, "rev-parse", "HEAD"], capture_output=True, text=True).stdout.strip() |
| 44 | if head != sr["commit"]: |
| 45 | sys.exit("semgrep-rules checkout is at %r, lock wants %s" % (head, sr["commit"])) |
| 46 | if yaml.__version__ != sr["pyyaml"]: |
| 47 | sys.exit("PyYAML %s, lock wants %s" % (yaml.__version__, sr["pyyaml"])) |
| 48 | data = build(root, lock) |
| 49 | got = hashlib.sha256(data).hexdigest() |
| 50 | if got != sr["config_sha256"]: |
| 51 | sys.exit("built config sha256 %s != lock %s" % (got, sr["config_sha256"])) |
| 52 | with open(out, "wb") as fh: |
| 53 | fh.write(data) |
| 54 | print("%s %s" % (got, out)) |
| 55 | |
| 56 | |
| 57 | if __name__ == "__main__": |
| 58 | main() |