#!/usr/bin/env python3
"""audit-verify.py - check an IndyKite Audit Log API export without the platform.

Usage: audit-verify.py <export-dir>

The directory is the one audit-export.sh writes:
  jwks*.json              the JWK Set current at export time, plus any earlier snapshots
  manifests/page-*.json   raw pages of GET /audit/v1/manifests
  logs/page-*.json        raw pages of GET /audit/v1/logs
  checkpoints/page-*.json raw pages of GET /audit/v1/checkpoints

Checks, per the Audit Log API guide:
  - every endpoint has its pages, numbered consecutively, each a valid envelope, with
    has_more true on every page but the last and next_cursor empty only on the last
  - manifests are contiguous from sequence 1 and each prev_hash equals the previous head_hash
  - head_hash recomputes as SHA-256 of "<project_id>|<sequence>|<prev_hash>|<data_hash>|<batch_id>"
  - batch hash recomputes as SHA-256 of the data array exactly as served, and equals data_hash
  - batch chain_hash, batch_id, manifest_id, sequence and project_id agree with the manifest;
    no sequence appears twice in logs/
  - every signature (alg ES256-DER: ECDSA P-256, DER, Base64) verifies under the JWK named by kid
  - every checkpoint signs "project-checkpoint|<project_id>|<sequence>|<head_hash>|<created_at>"
    and names the head the manifest at that sequence has

What this cannot tell you: whether the chain is complete. A valid prefix is still valid after
its tail is removed. Compare the newest sequence and head reported here with a value you kept
independently (the previous export, or a checkpoint fetched at another time), and authenticate
the JWKS you rely on independently of the party that handed you the export.

Requires Python 3.8+ and the "cryptography" package (pip install cryptography).
Exit code 0 when every check passes, 1 otherwise; failures are listed on stderr.
"""
import base64
import glob
import hashlib
import json
import os
import re
import sys

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import ec, utils

ALG = "ES256-DER"
PAGE_NAME = re.compile(r"^page-(\d{4,})\.json$")


class Fail(Exception):
    pass


# --- JSON scanning: the batch hash covers the data array exactly as served, so the raw bytes
# --- of each item's "data" value are taken from the page text instead of re-serializing it.

def _skip_ws(s, i):
    while i < len(s) and s[i] in " \t\r\n":
        i += 1
    return i


def _scan_string(s, i):
    i += 1
    while True:
        c = s[i]
        if c == "\\":
            i += 2
        elif c == '"':
            return i + 1
        else:
            i += 1


def _scan_value(s, i):
    c = s[i]
    if c == '"':
        return _scan_string(s, i)
    if c in "[{":
        depth = 0
        while True:
            c = s[i]
            if c == '"':
                i = _scan_string(s, i)
                continue
            if c in "[{":
                depth += 1
            elif c in "]}":
                depth -= 1
                if depth == 0:
                    return i + 1
            i += 1
    j = i
    while j < len(s) and s[j] not in ",]} \t\r\n":
        j += 1
    return j


def _members(s, i):
    """Yield (key, value_start, value_end) for the object starting at s[i] == '{'."""
    i = _skip_ws(s, i + 1)
    while s[i] != "}":
        kend = _scan_string(s, i)
        key = json.loads(s[i:kend])
        i = _skip_ws(s, kend)
        assert s[i] == ":"
        i = _skip_ws(s, i + 1)
        vend = _scan_value(s, i)
        yield key, i, vend
        i = _skip_ws(s, vend)
        if s[i] == ",":
            i = _skip_ws(s, i + 1)


def _elements(s, i):
    """Yield (start, end) for each element of the array starting at s[i] == '['."""
    i = _skip_ws(s, i + 1)
    while s[i] != "]":
        end = _scan_value(s, i)
        yield i, end
        i = _skip_ws(s, end)
        if s[i] == ",":
            i = _skip_ws(s, i + 1)


def raw_items(page_text):
    """Return [(item_dict, raw_data_bytes_or_None)] for one page."""
    out = []
    start = _skip_ws(page_text, 0)
    for key, vs, ve in _members(page_text, start):
        if key != "items":
            continue
        for es, ee in _elements(page_text, vs):
            item = json.loads(page_text[es:ee])
            raw = None
            for k, ds, de in _members(page_text, es):
                if k == "data":
                    raw = page_text[ds:de].encode("utf-8")
            out.append((item, raw))
    return out


def load_items(dirname):
    """Load every page of one endpoint, checking the saved pagination is complete."""
    if not os.path.isdir(dirname):
        raise Fail(f"{dirname}: directory missing (incomplete export)")
    files = {}
    for p in glob.glob(os.path.join(dirname, "page-*.json")):
        m = PAGE_NAME.match(os.path.basename(p))
        if not m:
            raise Fail(f"{p}: unexpected page file name")
        files[int(m.group(1))] = p
    if not files:
        raise Fail(f"{dirname}: no response pages (incomplete export)")
    last = max(files)
    items = []
    for n in range(1, last + 1):
        p = files.get(n)
        if p is None:
            raise Fail(f"{dirname}: page {n:04d} is missing")
        with open(p, "r", encoding="utf-8", newline="") as f:
            text = f.read()
        try:
            env = json.loads(text)
        except ValueError:
            raise Fail(f"{p}: not valid JSON")
        if not isinstance(env, dict) or not isinstance(env.get("items"), list):
            raise Fail(f"{p}: not a response envelope")
        expect_more = n < last
        if env.get("has_more") is not expect_more:
            raise Fail(f"{p}: has_more is {env.get('has_more')!r}, but this is page {n} of {last} (truncated export?)")
        cursor = env.get("next_cursor")
        if not isinstance(cursor, str) or bool(cursor) != expect_more:
            raise Fail(f"{p}: next_cursor does not match has_more")
        items.extend(raw_items(text))
    return items


# --- keys and signatures

def b64url_int(s):
    return int.from_bytes(base64.urlsafe_b64decode(s + "=" * (-len(s) % 4)), "big")


def load_keys(export_dir):
    keys = {}
    for p in sorted(glob.glob(os.path.join(export_dir, "jwks*.json"))):
        with open(p, "r", encoding="utf-8") as f:
            for k in json.load(f).get("keys", []):
                if k.get("kty") != "EC" or k.get("crv") != "P-256":
                    continue
                keys[k["kid"]] = ec.EllipticCurvePublicNumbers(
                    b64url_int(k["x"]), b64url_int(k["y"]), ec.SECP256R1()
                ).public_key()
    if not keys:
        raise Fail("no EC P-256 key found in jwks*.json")
    return keys


def check_signature(keys, what, kid, alg, hex_digest, signature_b64):
    if alg != ALG:
        raise Fail(f"{what}: alg is {alg!r}, expected {ALG!r}")
    key = keys.get(kid)
    if key is None:
        raise Fail(f"{what}: kid {kid!r} is in none of the JWK Sets kept with the export")
    try:
        key.verify(
            base64.b64decode(signature_b64),
            bytes.fromhex(hex_digest),
            ec.ECDSA(utils.Prehashed(hashes.SHA256())),
        )
    except (InvalidSignature, ValueError) as e:
        raise Fail(f"{what}: signature does not verify under kid {kid!r} ({e.__class__.__name__})")


def sha256_hex(data):
    return hashlib.sha256(data).hexdigest()


# --- the chain

def verify(export_dir):
    failures = []
    keys = load_keys(export_dir)

    manifests = [m for m, _ in load_items(os.path.join(export_dir, "manifests"))]
    batches = {}
    for b, raw in load_items(os.path.join(export_dir, "logs")):
        seq = b["sequence"]
        if seq in batches:
            raise Fail(f"batch {seq}: sequence appears twice in logs/")
        batches[seq] = (b, raw)
    checkpoints = [c for c, _ in load_items(os.path.join(export_dir, "checkpoints"))]
    manifests.sort(key=lambda m: m["sequence"])

    heads = {}
    prev_head = ""
    expected_seq = 1
    for m in manifests:
        seq = m["sequence"]
        what = f"manifest {seq}"
        try:
            if seq != expected_seq:
                raise Fail(f"{what}: expected sequence {expected_seq}, gap or duplicate in the export")
            if m["prev_hash"] != prev_head:
                raise Fail(f"{what}: prev_hash does not match head_hash of manifest {seq - 1}")
            head = sha256_hex(
                f"{m['project_id']}|{seq}|{m['prev_hash']}|{m['data_hash']}|{m['batch_id']}".encode()
            )
            if head != m["head_hash"]:
                raise Fail(f"{what}: head_hash does not recompute from its fields")
            check_signature(keys, what, m["kid"], m["alg"], m["head_hash"], m["signature"])
        except Fail as e:
            failures.append(str(e))
        heads[seq] = m["head_hash"]
        prev_head = m["head_hash"]
        expected_seq = seq + 1

        what = f"batch {seq}"
        try:
            if seq not in batches:
                raise Fail(f"{what}: no batch in logs/ for this manifest (incomplete export?)")
            b, raw = batches[seq]
            for field in ("batch_id", "manifest_id", "project_id"):
                if b.get(field) != m.get(field):
                    raise Fail(f"{what}: {field} differs from the manifest")
            if raw is None:
                raise Fail(f"{what}: no data array")
            data_hash = sha256_hex(raw)
            if data_hash != b["hash"] or data_hash != m["data_hash"]:
                raise Fail(f"{what}: SHA-256 of data as served differs from hash / data_hash")
            if b["chain_hash"] != m["head_hash"]:
                raise Fail(f"{what}: chain_hash differs from the manifest head_hash")
            check_signature(keys, what, b["kid"], b["alg"], b["hash"], b["signature"])
        except Fail as e:
            failures.append(str(e))

    for seq in sorted(set(batches) - set(heads)):
        failures.append(f"batch {seq}: no manifest in manifests/ for this batch")

    for c in checkpoints:
        what = f"checkpoint {c['checkpoint_id']} (sequence {c['sequence']})"
        try:
            digest = sha256_hex(
                f"project-checkpoint|{c['project_id']}|{c['sequence']}|{c['head_hash']}|{c['created_at']}".encode()
            )
            check_signature(keys, what, c["kid"], c["alg"], digest, c["signature"])
            if c["sequence"] not in heads:
                raise Fail(f"{what}: no manifest at that sequence in the export")
            if heads[c["sequence"]] != c["head_hash"]:
                raise Fail(f"{what}: head_hash differs from the manifest at that sequence")
        except Fail as e:
            failures.append(str(e))

    events = sum(len(json.loads(raw)) for _, raw in batches.values() if raw is not None)
    kids = sorted({m["kid"] for m in manifests} | {b["kid"] for b, _ in batches.values()} | {c["kid"] for c in checkpoints})
    newest = manifests[-1]["sequence"] if manifests else 0
    print(f"manifests: {len(manifests)}  batches: {len(batches)}  events: {events}  checkpoints: {len(checkpoints)}")
    print(f"sequences: 1..{newest}  keys used: {', '.join(kids) or '-'}")
    if manifests:
        print(f"newest head: sequence {newest} = {manifests[-1]['head_hash']}  (compare with the value you kept)")
    if failures:
        for f in failures:
            print("FAIL " + f, file=sys.stderr)
        print(f"{len(failures)} check(s) failed", file=sys.stderr)
        return 1
    print("OK: every hash, link and signature verified")
    return 0


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(__doc__, file=sys.stderr)
        sys.exit(2)
    try:
        sys.exit(verify(sys.argv[1]))
    except Fail as e:
        print("FAIL " + str(e), file=sys.stderr)
        sys.exit(1)
