#!/usr/bin/env python3
"""Independent check of a gak.receipt.v2 Ed25519 signature, without gak-verify.

Usage: python3 check_receipt_v2.py RECEIPT.json JWKS.json [PINNED_KID]
Needs: pip install cryptography

It re-derives the signed bytes (RFC 8785 JCS of the body without "attestation";
a v2 body holds only strings, nulls, objects and arrays, so sorted keys and
compact separators give the JCS form), checks the domain-separated payload
digest, and verifies the Ed25519 signature against the key in the JWKS.
It is a reading aid for the published spec, not a replacement for gak-verify:
it does not check the member set, executor statements or the v1 link.
"""
import base64, hashlib, json, sys
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
from cryptography.exceptions import InvalidSignature

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

def main() -> int:
    receipt = json.load(open(sys.argv[1], encoding="utf-8"))
    jwks = json.load(open(sys.argv[2], encoding="utf-8"))
    pinned = sys.argv[3] if len(sys.argv) > 3 else None
    att = receipt.pop("attestation")
    if receipt.get("schema_version") != "gak.receipt.v2" or att.get("alg") != "Ed25519":
        print("FAIL UNSUPPORTED"); return 1
    signed = json.dumps(receipt, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    digest = "sha256:" + hashlib.sha256(b"gak:receipt:v2\n" + signed).hexdigest()
    if digest != att["payload_digest"]:
        print("FAIL PAYLOAD_DIGEST_MISMATCH"); return 1
    if pinned and att["key_id"] != pinned:
        print("FAIL KEY_PIN_MISMATCH"); return 1
    keys = [k for k in jwks["keys"] if k.get("kid") == att["key_id"]]
    if not keys:
        print("FAIL UNKNOWN_KEY_ID"); return 1
    if hashlib.sha256(signed).hexdigest() != att["signed_bytes_sha256"]:
        print("FAIL SIGNED_BYTES_DIGEST_MISMATCH"); return 1
    try:
        Ed25519PublicKey.from_public_bytes(b64u(keys[0]["x"])).verify(b64u(att["signature"]), signed)
    except InvalidSignature:
        print("FAIL SIGNATURE_INVALID"); return 1
    print("PASS", receipt["terminal_outcome"], receipt["receipt_id"])
    return 0

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