#!/usr/bin/env python3
"""Check an Arc evidence bundle without trusting Arc.

    python verify_evidence_bundle.py bundle.json [--public-key KEY]

Standalone: needs only Python 3.10+ (and the `cryptography` package to check
the signature). It recomputes, for every entry in the bundle:

  payload_hash = sha256(payload_text)                       (for disclosed records)
  entry_hash   = sha256("arc-evidence-v1|org|seq|prev_hash|table|record_id|op|payload_hash|created_at")

and checks that each entry links to the one before it, that the last entry is
the signed head, and that Arc's Ed25519 signature on the head is valid. Pass
--public-key with the key Arc publishes (GET /v1/evidence/public-key) to pin
it; otherwise the key inside the bundle is used and its id is printed so you
can compare it.

Exit code 0: the bundle is intact. 1: it is not (the reasons are printed).
"""

from __future__ import annotations

import argparse
import base64
import hashlib
import json
import sys


def sha256_hex(text: str) -> str:
    return hashlib.sha256(text.encode("utf-8")).hexdigest()


def entry_hash(org: str, e: dict) -> str:
    return sha256_hex("|".join([
        "arc-evidence-v1", org, str(e["seq"]), e["prev_hash"], e["record_table"], e["record_id"], e["operation"],
        e["payload_hash"], e["created_at"],
    ]))


def _unb64(text: str) -> bytes:
    return base64.urlsafe_b64decode(text + "=" * (-len(text) % 4))


def verify(bundle: dict, public_key: str | None = None) -> list[str]:
    problems: list[str] = []
    if bundle.get("format") != "arc-evidence-bundle-v1":
        return ["not an arc-evidence-bundle-v1 file"]
    org, entries, head = bundle["organisation_id"], bundle["entries"], bundle["head"]
    if not entries:
        return ["the bundle has no entries"]
    for i, e in enumerate(entries):
        if i and e["seq"] != entries[i - 1]["seq"] + 1:
            problems.append(f"entry {entries[i - 1]['seq'] + 1} is missing")
        if i and e["prev_hash"] != entries[i - 1]["entry_hash"]:
            problems.append(f"entry {e['seq']} does not link to the entry before it")
        if "payload_text" in e and sha256_hex(e["payload_text"]) != e["payload_hash"]:
            problems.append(f"entry {e['seq']}: the disclosed record does not match its hash")
        if entry_hash(org, e) != e["entry_hash"]:
            problems.append(f"entry {e['seq']}: its hash is wrong")
    last = entries[-1]
    if (last["seq"], last["entry_hash"]) != (head["seq"], head["head_hash"]):
        problems.append("the last entry is not the signed head")
    disclosed = {(e["record_table"], e["record_id"]) for e in entries if "payload_text" in e}
    for r in bundle.get("related", []):
        if (r["record_table"], r["record_id"]) not in disclosed:
            problems.append(f"{r['record_table']} {r['record_id']} is listed but not disclosed")

    sig = head.get("signature")
    if not sig:
        problems.append("the head is not signed (Arc's signing key is not configured)")
    else:
        try:
            from cryptography.exceptions import InvalidSignature
            from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
        except ImportError:
            problems.append("install the 'cryptography' package to check the signature")
        else:
            key = public_key or sig["public_key"]
            message = f"arc-evidence-head-v1|{org}|{head['seq']}|{head['head_hash']}|{head['signed_at']}".encode()
            try:
                Ed25519PublicKey.from_public_bytes(_unb64(key)).verify(_unb64(sig["signature"]), message)
            except (InvalidSignature, ValueError):
                problems.append("Arc's signature on the head is not valid for this key")
            if public_key is None:
                print(f"Signed with key {sig['key_id']} (from the bundle). Compare it with Arc's published key.")
    return problems


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("bundle")
    parser.add_argument("--public-key", help="Arc's published public key (URL-safe base64)")
    args = parser.parse_args()
    with open(args.bundle, encoding="utf-8") as f:
        bundle = json.load(f)
    problems = verify(bundle, args.public_key)
    if problems:
        print("NOT VERIFIED:")
        for p in problems:
            print(f"  - {p}")
        return 1
    n = len(bundle["entries"])
    print(f"Verified: {n} chain entries up to signed head {bundle['head']['seq']}, "
          f"{len(bundle['related'])} records of decision {bundle['decision_id']} intact.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
