#!/usr/bin/env python3
"""Check a PROOFLOOP record against Sigstore Rekor, without trusting FIRME AI CORPORATION.

You give it the key fingerprint you got from somewhere other than our site (for example the LinkedIn post). It:
  1. reads our published anchor list to learn WHICH Rekor entry to look at (that list is only a pointer: nothing in
     it is trusted);
  2. fetches that entry from rekor.sigstore.dev itself and checks its RFC 9162 inclusion proof and checkpoint;
  3. takes the public key out of the Rekor entry and requires its SHA-256 fingerprint to equal yours;
  4. fetches the anchored head record and checks its hash and its Ed25519 signature with THAT key, and that the
     signature is exactly the one in the log;
  5. walks the chain back from the head (each record's prev_record_hash) to the record you name, checking every
     hash, signature and link on the way.

If every check holds it prints ANCHORED: the record existed, unchanged, under that key, no later than Rekor's
integrated time. Anything else prints NOT_VERIFIED with the reason. Records newer than the latest anchored head
are covered by the next daily anchor.

  pip install cryptography
  python3 -I verify_keystone_rekor.py --fingerprint SHA256:<hex> [--run-id <run_id>] [--site https://cainstudio.online]

Standard library plus `cryptography`; imports no CAIN code.
"""
from __future__ import annotations

import argparse
import base64
import hashlib
import json
import sys
import urllib.parse
import urllib.request

REKOR = "https://rekor.sigstore.dev"
SAMPLE_RUN = "ks-20261105T225548Z-4f35c76d"   # the published PROOFLOOP sample


def _get(url: str):
    req = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": "verify-keystone-rekor"})
    with urllib.request.urlopen(req, timeout=60) as r:
        return json.loads(r.read())


def _h(b: bytes) -> bytes:
    return hashlib.sha256(b).digest()


def _verify_inclusion(index: int, size: int, leaf: bytes, proof: list, root: bytes) -> bool:
    """RFC 9162 section 2.1.3.2 audit-path verification."""
    if index >= size:
        return False
    fn, sn, r = index, size - 1, leaf
    for p in proof:
        if sn == 0:
            return False
        if fn & 1 or fn == sn:
            r = _h(b"\x01" + p + r)
            if not fn & 1:
                while fn and not fn & 1:
                    fn >>= 1
                    sn >>= 1
        else:
            r = _h(b"\x01" + r + p)
        fn >>= 1
        sn >>= 1
    return sn == 0 and r == root


SPKI_ED25519_PREFIX = bytes.fromhex("302a300506032b6570032100")


def _pem_to_raw(pem: str) -> bytes:
    """The raw 32-byte key from an Ed25519 SubjectPublicKeyInfo PEM; anything else is refused."""
    der = base64.b64decode("".join(l for l in pem.strip().splitlines() if "-----" not in l))
    if len(der) != 44 or not der.startswith(SPKI_ED25519_PREFIX):
        raise ValueError("the key in the Rekor entry is not an Ed25519 public key")
    return der[12:]


def _canon(obj) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def _check_record(rec: dict, key) -> list:
    from cryptography.exceptions import InvalidSignature
    problems = []
    body = {k: v for k, v in rec.items() if k not in ("record_hash", "signature_b64", "public_key_b64")}
    if hashlib.sha256(_canon(body)).hexdigest() != rec.get("record_hash"):
        problems.append(f"record {rec.get('run_id')}: content does not match record_hash")
    try:
        key.verify(base64.b64decode(rec.get("signature_b64", "")), str(rec.get("record_hash", "")).encode())
    except (InvalidSignature, ValueError):
        problems.append(f"record {rec.get('run_id')}: signature does not verify with the Rekor-logged key")
    return problems


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--fingerprint", required=True, help="SHA256:<hex> of the PROOFLOOP key, from a source you trust")
    ap.add_argument("--run-id", default=SAMPLE_RUN, help="the record to check (default: the published sample)")
    ap.add_argument("--site", default="https://cainstudio.online")
    ap.add_argument("--rekor", default=REKOR)
    a = ap.parse_args(argv)
    from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

    def fail(msg: str) -> int:
        print(f"  [FAIL] {msg}")
        print("NOT_VERIFIED")
        return 1

    want = a.fingerprint.strip().lower().removeprefix("sha256:")
    doc = _get(f"{a.site}/evidence/keystone-rekor/rekor-anchors.json")      # a pointer only
    latest = doc.get("latest") or {}
    uuid = latest.get("rekor_uuid", "")
    if not uuid:
        return fail("no anchor has been published yet")
    print(f"  Rekor entry {uuid} (log index {latest.get('log_index')}), fetched from {a.rekor}")
    resp = _get(f"{a.rekor}/api/v1/log/entries/{urllib.parse.quote(uuid)}")
    entry = resp.get(uuid) or next(iter(resp.values()))
    body_bytes = base64.b64decode(entry["body"])
    spec = json.loads(body_bytes).get("spec", {})
    proof = (entry.get("verification") or {}).get("inclusionProof") or {}
    if not proof or not _verify_inclusion(int(proof["logIndex"]), int(proof["treeSize"]), _h(b"\x00" + body_bytes),
                                          [bytes.fromhex(x) for x in proof["hashes"]], bytes.fromhex(proof["rootHash"])):
        return fail("the Rekor inclusion proof does not reach the stated root")
    cp = proof.get("checkpoint", "").splitlines()
    if len(cp) < 3 or base64.b64decode(cp[2]).hex() != proof["rootHash"] or cp[1] != str(proof["treeSize"]):
        return fail("the Rekor checkpoint does not match the proof's root and tree size")
    print(f"  [PASS] inclusion proof verifies to the Rekor root (tree size {proof['treeSize']})")
    raw = _pem_to_raw(base64.b64decode(spec["signature"]["publicKey"]["content"]).decode())
    got = hashlib.sha256(raw).hexdigest()
    if got != want:
        return fail(f"the key in Rekor is SHA256:{got}, not the fingerprint you gave")
    print(f"  [PASS] the key logged in Rekor has your fingerprint SHA256:{got}")
    key = Ed25519PublicKey.from_public_bytes(raw)

    runs = {r["run_id"]: r for r in _get(f"{a.site}/keystone/runs?limit=200")["runs"]}
    head = _get(f"{a.site}/keystone/runs/{urllib.parse.quote(latest['head_run_id'])}")
    problems = _check_record(head, key)
    if problems:
        return fail("; ".join(problems))
    if hashlib.sha256(head["record_hash"].encode()).hexdigest() != spec["data"]["hash"]["value"]:
        return fail("the anchored head's record_hash is not the data logged in Rekor")
    if spec["signature"]["content"] != head["signature_b64"]:
        return fail("the head's signature is not the signature logged in Rekor")
    print(f"  [PASS] head {head['run_id']} (sequence {head.get('sequence')}) is the logged data, signed by that key")

    by_hash = {r["record_hash"]: r["run_id"] for r in runs.values()}
    cur, steps = head, 0
    while cur["run_id"] != a.run_id:
        prev_id = by_hash.get(cur.get("prev_record_hash"))
        if not prev_id:
            return fail(f"{a.run_id} is not an ancestor of the anchored head (chain ends at {cur['run_id']}); "
                        "if it is newer than the head, the next daily anchor covers it")
        prev = _get(f"{a.site}/keystone/runs/{urllib.parse.quote(prev_id)}")
        problems = _check_record(prev, key)
        if problems:
            return fail("; ".join(problems))
        if prev["record_hash"] != cur.get("prev_record_hash"):
            return fail(f"{cur['run_id']} does not link to {prev_id}")
        cur, steps = prev, steps + 1
    print(f"  [PASS] {steps} signed link(s) from the anchored head back to {a.run_id}; every hash and signature holds")
    print(f"ANCHORED: {a.run_id} (record_hash {cur['record_hash'][:16]}...) existed unchanged, under key "
          f"SHA256:{got[:16]}..., no later than {latest.get('integrated_time_utc')} (Sigstore Rekor, not us)")
    return 0


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