#!/usr/bin/env python3
"""Verify an SPE 1.0 proof locally. Python 3.9+. Optional Ed25519 support via PyNaCl.

Run a copy of this verifier obtained from a trusted source. The three proof records
are checked. Additional documents in a delivery are neither read nor authenticated.
A valid signature identifies the included key; establish its owner independently.
Exit 0: valid proof (and matching original when given). Exit 1: invalid evidence or
different original. Exit 2: unsupported format, missing capability or input error.
"""

import argparse
import base64
import binascii
import hashlib
import json
import os
from pathlib import Path
import re
import sqlite3
import sys
import tempfile
import zipfile
import zlib
from contextlib import closing

KIB = 1024
MAX_ARCHIVE = 4 * 1024 * KIB
CORE = {"forensic_capsule.json": 128 * KIB, "proof_input.json": 128 * KIB,
        "ledger.sqlite": 2048 * KIB}
HEX_HASH = re.compile(r"[a-f0-9]{64}")
LEDGER_SCHEMA = ("CREATE TABLE ledger (id INTEGER PRIMARY KEY AUTOINCREMENT, "
                 "t_run INTEGER NOT NULL, capsule_hash TEXT NOT NULL, "
                 "prev_hash TEXT NOT NULL, entry_hash TEXT NOT NULL)")


class Invalid(ValueError):
    """The supplied proof is malformed or internally inconsistent."""


class Unsupported(Exception):
    """This reader cannot verify the supplied input."""


def require(value, message):
    if not value:
        raise Invalid(message)


def read_records(path):
    if not path.is_file():
        raise OSError("proof is not a regular file")
    with path.open("rb") as src:
        if os.fstat(src.fileno()).st_size > MAX_ARCHIVE:
            raise Unsupported("archive exceeds the 4 MiB verification limit")
        with zipfile.ZipFile(src) as archive:
            entries = archive.infolist()
            if len(entries) > 64:
                raise Unsupported("archive exceeds the 64-entry limit")
            names = [item.orig_filename for item in entries]
            require(len(names) == len(set(names)), "duplicate ZIP member name")
            require(all(item.orig_filename == item.filename for item in entries),
                    "ambiguous ZIP member name")
            if not CORE.keys() <= set(names):
                raise Invalid("missing one or more of the three required proof records")
            records = {}
            for name, limit in CORE.items():
                item = archive.getinfo(name)
                if item.flag_bits & 1 or item.compress_type not in (zipfile.ZIP_DEFLATED, zipfile.ZIP_STORED):
                    raise Unsupported("encrypted or unsupported compression in " + name)
                if item.file_size > limit:
                    raise Unsupported(name + " exceeds its verification size limit")
                with archive.open(item) as member:
                    data = member.read(limit + 1)
                require(len(data) == item.file_size, "invalid member size: " + name)
                records[name] = data
            return records


def distinct_keys(pairs):
    result = {}
    for key, value in pairs:
        require(key not in result, "duplicate JSON key")
        result[key] = value
    return result


def invalid_constant(value):
    raise Invalid("invalid non-finite JSON number")


def json_record(data):
    item = json.loads(data.decode("utf-8"), object_pairs_hook=distinct_keys,
                      parse_constant=invalid_constant)
    require(isinstance(item, dict), "expected a JSON object")
    return item


def canonical(item):
    return json.dumps(item, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
                      allow_nan=False).encode("utf-8")


def safe_int(value):
    return type(value) is int and abs(value) <= 2**53 - 1


def check_manifest(capsule, manifest):
    mode = manifest.get("mode")
    if mode not in ("file", "text", "hash-only") or manifest.get("schema_version") != "proof-input-" + mode + "/1.0":
        raise Unsupported("unsupported proof-input version or mode")
    if capsule.get("hash_alg") != "sha256" or manifest.get("hash_algorithm") != "sha256":
        raise Unsupported("unsupported hash algorithm")
    digest = manifest.get("hash_value")
    require(isinstance(digest, str) and HEX_HASH.fullmatch(digest), "invalid SHA-256")
    require(capsule.get("output_hash") == "sha256:" + digest, "capsule and manifest hashes differ")
    require(all(safe_int(value) for value in (capsule.get("t_run"), capsule.get("t_target"),
                                              manifest.get("t_run"))), "invalid timestamp")
    require(all(isinstance(capsule.get(k), str) for k in
                ("model_id", "artifact_type", "gate_policy_id", "context_merkle_root", "hash_prompt")),
            "incomplete capsule")
    require(all(capsule.get(k) == manifest.get(k) for k in ("mode", "t_run", "artifact_type", "model_id")),
            "capsule and manifest fields differ")
    context = manifest.get("context")
    require(isinstance(context, dict) and context.get("domain") == capsule["artifact_type"] and
            context.get("purpose") == "attestation", "invalid manifest context")
    return digest


def normalized_schema(sql):
    return "".join(sql.lower().split()).rstrip(";")


def check_ledger(raw, capsule):
    require(raw.startswith(b"SQLite format 3\0"), "invalid ledger header")
    capsule_hash = hashlib.sha256(canonical(capsule)).hexdigest()
    with tempfile.TemporaryDirectory(prefix="spe-verify-") as temp:
        path = Path(temp, "ledger.sqlite")
        path.write_bytes(raw)
        with closing(sqlite3.connect(path.as_uri() + "?mode=ro&immutable=1", uri=True)) as db:
            db.execute("PRAGMA trusted_schema=OFF")
            db.execute("PRAGMA query_only=ON")
            # The ordinary table and fixed query suffice. Never run supplied SQL.
            budget = iter(range(2000))
            db.set_progress_handler(lambda: next(budget, None) is None, 1000)
            schema = db.execute("SELECT type,sql FROM sqlite_master WHERE name='ledger'").fetchone()
            if not schema or schema[0] != "table" or normalized_schema(schema[1] or "") != normalized_schema(LEDGER_SCHEMA):
                raise Unsupported("unknown ledger schema")
            previous, last_id, last_time, last_hash = "0" * 64, 0, None, None
            rows = db.execute("SELECT id,t_run,capsule_hash,prev_hash,entry_hash "
                              "FROM ledger NOT INDEXED ORDER BY id LIMIT 10001")
            for count, (entry_id, timestamp, current, prev, entry) in enumerate(rows, 1):
                if count > 10000:
                    raise Unsupported("ledger exceeds the 10000-entry verification limit")
                require(safe_int(entry_id) and entry_id > last_id and safe_int(timestamp), "invalid ledger row")
                require(isinstance(current, str) and HEX_HASH.fullmatch(current) and prev == previous,
                        "broken ledger chain")
                expected = hashlib.sha256(f"{previous}|{current}|{timestamp}".encode("ascii")).hexdigest()
                require(entry == expected, "invalid ledger entry hash")
                previous, last_id, last_time, last_hash = entry, entry_id, timestamp, current
            require(last_time == capsule["t_run"] and last_hash == capsule_hash, "ledger tip does not match capsule")


def signature_status(manifest):
    if "signature" not in manifest:
        return "UNSIGNED"
    signature = manifest["signature"]
    if not isinstance(signature, dict) or signature.get("algorithm") != "ed25519":
        return "INVALID"
    try:
        public = base64.b64decode(signature["public_key"], validate=True)
        signed = base64.b64decode(signature["signature_value"], validate=True)
        if len(public) != 32 or len(signed) != 64:
            return "INVALID"
    except (KeyError, TypeError, ValueError, binascii.Error):
        return "INVALID"
    try:
        from nacl.exceptions import BadSignatureError
        from nacl.signing import VerifyKey
    except (ImportError, OSError):
        return "UNAVAILABLE"
    payload = {k: v for k, v in manifest.items() if k != "signature"}
    try:
        VerifyKey(public).verify(canonical(payload), signed)
    except BadSignatureError:
        return "INVALID"
    return "VALID"


def file_hash(path):
    if not path.is_file():
        raise OSError("original is not a regular file")
    digest = hashlib.sha256()
    with path.open("rb") as original:
        for chunk in iter(lambda: original.read(1024 * KIB), b""):
            digest.update(chunk)
    return digest.hexdigest()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("proof", type=Path)
    parser.add_argument("original", type=Path, nargs="?")
    args = parser.parse_args()
    integrity, signature, digest = "NOT_CHECKED", "NOT_CHECKED", "NOT_CHECKED"
    original = "NOT_CHECKED" if args.original else "NOT_PROVIDED"
    result = 0
    try:
        records = read_records(args.proof)
        capsule = json_record(records["forensic_capsule.json"])
        manifest = json_record(records["proof_input.json"])
        digest = check_manifest(capsule, manifest)
        check_ledger(records["ledger.sqlite"], capsule)
        integrity = "VALID"
        signature = signature_status(manifest)
        if signature == "INVALID":
            result = 1
        elif signature == "UNAVAILABLE":
            print("Ed25519 verification requires PyNaCl in this Python environment.", file=sys.stderr)
            result = 2
        if args.original:
            original = "MATCH" if file_hash(args.original) == digest else "MISMATCH"
            if original == "MISMATCH":
                result = 1
    except (OSError, Unsupported, NotImplementedError) as exc:
        print(str(exc), file=sys.stderr)
        result = 2 if result == 0 else result
    except (ValueError, zipfile.BadZipFile, EOFError, sqlite3.DatabaseError, zlib.error, RecursionError) as exc:
        print("Invalid proof: " + str(exc), file=sys.stderr)
        integrity, result = "INVALID", 1
    print("Integrity:", integrity)
    print("Signature:", signature)
    print("Original:", original)
    print("SHA-256:", digest)
    return result


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