#!/usr/bin/env python3 """Verify a molCore DataRoom audit export (proposal ยง5.7 point 3). An export is a directory (or a bucket prefix downloaded with `gcloud storage cp -r`) holding `manifest.json`, `manifest.sig` and the data files the manifest lists. This tool checks, in order: 1. the signature in manifest.sig verifies over the exact bytes of manifest.json with the public key you pass (`--public-key`), or with the key the manifest names when `keys/.pem` sits next to the export (`--keys-dir`); 2. every file the manifest lists is present with the recorded sha256 and size; TRUST ANCHOR. Only `--public-key`, with a key obtained OUT OF BAND (from https://dataroom.molcore.bio/security/audit-sign.pem, or `gcloud kms keys versions get-public-key`), is evidence that molCore signed the export: the tool then refuses a manifest naming any other key. With `--keys-dir` alone the key comes from beside the export it verifies, so whoever could replace the export could replace that key and the manifest's `public_key_sha256` together, and the checks still pass; that mode proves INTEGRITY of the download (nothing changed since it was written) and nothing about who wrote it. The report says which anchor was used (`trust_anchor: out-of-band | manifest-named`) and prints a WARN line for the latter. Counsel and investors: always pass `--public-key`. 3. the row counts and first/last ids in the manifest match the JSONL content; 4. the CSV of each table has the same number of data rows as its JSONL; 5. with `--previous DIR`, that the manifest's previous_manifest names the previous day's manifest and its sha256 (the chain). Exit 0: everything verified. Exit 1: at least one check failed (each failure is printed). Exit 2: usage error. Needs Python 3.10+ and the `cryptography` package (`pip install cryptography`); nothing else. python3 tools/verify_export.py daily/2026-11-03 --public-key audit-sign.pem python3 tools/verify_export.py daily/2026-11-03 --public-key audit-sign.pem --previous daily/2026-11-02 python3 tools/verify_export.py daily/2026-11-03 --public-key audit-sign.pem --json python3 tools/verify_export.py daily/2026-11-03 --keys-dir . # integrity only, prints WARN The public key of the PROD signing key is published at https://dataroom.molcore.bio/security/ next to this tool. """ from __future__ import annotations import argparse import base64 import csv import hashlib import io import json import sys from pathlib import Path try: from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec, ed25519 except ImportError: # pragma: no cover print("verify_export.py needs the 'cryptography' package: pip install cryptography", file=sys.stderr) sys.exit(2) def sha256_hex(data: bytes) -> str: return hashlib.sha256(data).hexdigest() def verify_signature(public_key_pem: bytes, data: bytes, signature: bytes) -> str: key = serialization.load_pem_public_key(public_key_pem) try: if isinstance(key, ec.EllipticCurvePublicKey): key.verify(signature, data, ec.ECDSA(hashes.SHA256())) return "EC_SIGN_P256_SHA256" if isinstance(key, ed25519.Ed25519PublicKey): key.verify(signature, data) return "ED25519" except InvalidSignature as exc: raise ValueError("signature does not verify") from exc raise ValueError(f"unsupported key type {type(key).__name__}") def read_signature(path: Path) -> bytes: raw = path.read_bytes() text = raw.strip() try: return base64.b64decode(text, validate=True) except (ValueError, Exception): return raw def jsonl_rows(data: bytes) -> list[dict]: rows = [] for n, line in enumerate(data.decode("utf-8").splitlines(), 1): if not line.strip(): continue try: rows.append(json.loads(line)) except json.JSONDecodeError as exc: raise ValueError(f"line {n}: {exc}") from exc return rows def csv_row_count(data: bytes) -> int: reader = csv.reader(io.StringIO(data.decode("utf-8"), newline="")) return max(sum(1 for _ in reader) - 1, 0) MANIFEST_NAMED_WARNING = ( "the signing key was taken from beside the export (--keys-dir), as the manifest names it: " "this proves the download is unchanged, not who signed it; pass --public-key with the key " "from /security/audit-sign.pem (or gcloud kms keys versions get-public-key) for evidence" ) def verify(export_dir: Path, *, public_key: Path | None, keys_dir: Path | None, previous: Path | None) -> dict: problems: list[str] = [] warnings: list[str] = [] result = {"export": str(export_dir), "problems": problems, "warnings": warnings, "trust_anchor": None} manifest_path = export_dir / "manifest.json" sig_path = export_dir / "manifest.sig" if not manifest_path.is_file(): problems.append("manifest.json missing") return result manifest_bytes = manifest_path.read_bytes() result["manifest_sha256"] = sha256_hex(manifest_bytes) try: manifest = json.loads(manifest_bytes) except json.JSONDecodeError as exc: problems.append(f"manifest.json unreadable: {exc}") return result result["kind"] = manifest.get("kind") result["date"] = manifest.get("date") or manifest.get("through") # 1. signature pem = None if public_key is not None: pem = public_key.read_bytes() result["trust_anchor"] = "out-of-band" elif keys_dir is not None: named = manifest.get("public_key_path", "") candidate = keys_dir / named if candidate.is_file(): pem = candidate.read_bytes() result["trust_anchor"] = "manifest-named" warnings.append(MANIFEST_NAMED_WARNING) else: problems.append(f"public key {named or '(unnamed)'} not found under {keys_dir}") else: problems.append("no public key given (--public-key or --keys-dir)") if pem is not None: signer = manifest.get("signer") or {} if signer.get("public_key_sha256") and signer["public_key_sha256"] != sha256_hex(pem): problems.append("the key given is not the key the manifest names (public_key_sha256 differs)") if not sig_path.is_file(): problems.append("manifest.sig missing") else: try: result["algorithm"] = verify_signature(pem, manifest_bytes, read_signature(sig_path)) except ValueError as exc: problems.append(f"signature: {exc}") # 2-4. files, hashes, counts files = manifest.get("files") or {} if not files: problems.append("manifest lists no files") jsonl_counts: dict[str, int] = {} for name, meta in files.items(): path = export_dir / name if not path.is_file(): problems.append(f"{name}: missing") continue data = path.read_bytes() if sha256_hex(data) != meta.get("sha256"): problems.append(f"{name}: sha256 differs from the manifest") if meta.get("bytes") is not None and len(data) != meta["bytes"]: problems.append(f"{name}: size {len(data)} differs from the manifest's {meta['bytes']}") if name.endswith(".jsonl"): try: rows = jsonl_rows(data) except ValueError as exc: problems.append(f"{name}: {exc}") continue jsonl_counts[name[:-len(".jsonl")]] = len(rows) if meta.get("rows") is not None and meta["rows"] != len(rows): problems.append(f"{name}: {len(rows)} rows, manifest says {meta['rows']}") ids = [r.get("id") for r in rows if isinstance(r.get("id"), int)] if ids: if meta.get("first_id") != min(ids) or meta.get("last_id") != max(ids): problems.append(f"{name}: id range {min(ids)}..{max(ids)} differs from the manifest") elif meta.get("first_id") is not None: problems.append(f"{name}: manifest records ids but the file has none") for name, meta in files.items(): if name.endswith(".csv"): stem = name[:-len(".csv")] path = export_dir / name if stem in jsonl_counts and path.is_file(): count = csv_row_count(path.read_bytes()) if count != jsonl_counts[stem]: problems.append(f"{name}: {count} data rows, {stem}.jsonl has {jsonl_counts[stem]}") result["files_checked"] = len(files) # 5. chain prev = manifest.get("previous_manifest") if previous is not None: prev_bytes = (previous / "manifest.json").read_bytes() if (previous / "manifest.json").is_file() else None if prev_bytes is None: problems.append(f"--previous: {previous}/manifest.json missing") elif not prev: problems.append("manifest names no previous_manifest but --previous was given") elif prev.get("sha256") != sha256_hex(prev_bytes): problems.append("chain: previous_manifest.sha256 differs from the previous manifest's hash") else: result["chain"] = "ok" result["ok"] = not problems return result def main(argv=None) -> int: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("export_dir", type=Path, help="directory holding manifest.json, manifest.sig and the files") ap.add_argument("--public-key", type=Path, help="PEM of the signing key's public half obtained out of band (from /security/); " "the only mode that is evidence of who signed") ap.add_argument("--keys-dir", type=Path, help="directory holding keys/.pem as exported; integrity check only " "(the key sits beside what it verifies), prints WARN") ap.add_argument("--previous", type=Path, help="the previous export's directory, to check the chain") ap.add_argument("--json", action="store_true") args = ap.parse_args(argv) if not args.export_dir.is_dir(): print(f"not a directory: {args.export_dir}", file=sys.stderr) return 2 result = verify(args.export_dir, public_key=args.public_key, keys_dir=args.keys_dir, previous=args.previous) if args.json: print(json.dumps(result, indent=2)) else: for w in result.get("warnings", []): print(f"WARN {w}") for p in result["problems"]: print(f"FAIL {p}") if result.get("ok"): print(f"OK {result['export']}: {result.get('kind')} {result.get('date')} " f"({result.get('algorithm')}, {result.get('files_checked')} files" f"{', chain ok' if result.get('chain') == 'ok' else ''}; " f"trust anchor: {result.get('trust_anchor')})") return 0 if result.get("ok") else 1 if __name__ == "__main__": sys.exit(main())