#!/usr/bin/env python3
"""Verify a TraceForge release locally. Never uploads files or executes the installer."""
import argparse
import base64
import hashlib
import json
import re
from pathlib import Path

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey

# Enrolled public release key, not a key chosen by the signature envelope.
TRUSTED_KEY = 'OVwFtHoPgdEdezdHyf2DUtxX/Q4nUKgUBxZx0anX1Q8='
KEY_ID = '477c2401bb8ff4338ae6e30d8f21d981'


def canonical(value):
    return json.dumps(value, allow_nan=False, ensure_ascii=True,
                      sort_keys=True, separators=(',', ':')).encode()


def signed_digest(document, name):
    """Accept the enrolled legacy and current release protocols, never a new key."""
    if document.get('key_id') != KEY_ID:
        raise ValueError('Wrong release key')
    public = base64.b64decode(TRUSTED_KEY, validate=True)
    key = Ed25519PublicKey.from_public_bytes(public)
    if document.get('schema_version') == 'traceforge.detached-signature.v1':
        if document.get('algorithm') != 'ed25519' or document.get('artifact_path') != name:
            raise ValueError('Wrong legacy release identity')
        digest = document.get('artifact_sha256')
        if not isinstance(digest, str) or not re.fullmatch('[0-9a-f]{64}', digest):
            raise ValueError('Invalid release digest')
        key.verify(base64.b64decode(document['signature_base64'], validate=True),
                   bytes.fromhex(digest))
        return digest
    if (document.get('schema_version') != 'traceforge.distribution_signature.v1'
            or document.get('algorithm') != 'Ed25519'):
        raise ValueError('Unsupported signature format')
    unsigned = {k: v for k, v in document.items() if k != 'payload_sha256'}
    if document.get('payload_sha256') != hashlib.sha256(canonical(unsigned)).hexdigest():
        raise ValueError('Signature document integrity mismatch')
    if base64.b64decode(document['public_key_b64'], validate=True) != public:
        raise ValueError('Unenrolled release key')
    payload = document.get('payload')
    required = {'package_name', 'package_sha256', 'platform', 'source_sha'}
    if (not isinstance(payload, dict) or not required <= payload.keys()
            or payload.keys() - required - {'architecture', 'package_profile'}):
        raise ValueError('Invalid release identity')
    if payload['package_name'] != name:
        raise ValueError('Wrong artifact name')
    platforms = {'linux': {'amd64', 'arm64'}, 'windows': {'x64'}}
    if payload['platform'] not in platforms:
        raise ValueError('Unsupported release platform')
    if ('architecture' in payload
            and payload['architecture'] not in platforms[payload['platform']]):
        raise ValueError('Unsupported release architecture')
    if ('package_profile' in payload
            and payload['package_profile'] != 'traceforge.customer_engine.v1'):
        raise ValueError('Unsupported package profile')
    if not isinstance(payload['source_sha'], str) or not re.fullmatch('[0-9a-f]{40}|[0-9a-f]{64}', payload['source_sha']):
        raise ValueError('Invalid source revision')
    digest = payload['package_sha256']
    if not isinstance(digest, str) or not re.fullmatch('[0-9a-f]{64}', digest):
        raise ValueError('Invalid release digest')
    key.verify(base64.b64decode(document['signature_b64'], validate=True), canonical(payload))
    return digest


def verify(artifact, signature):
    if signature.stat().st_size > 64 * 1024:
        raise ValueError('Signature document is too large')
    document = json.loads(signature.read_text(encoding='utf-8'))
    expected = signed_digest(document, artifact.name)
    digest = hashlib.sha256()
    with artifact.open('rb') as handle:
        for chunk in iter(lambda: handle.read(1024 * 1024), b''):
            digest.update(chunk)
    if expected != digest.hexdigest():
        raise ValueError('The file does not match the signed digest')
    return digest.hexdigest()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('installer', type=Path)
    parser.add_argument('signature', type=Path)
    args = parser.parse_args()
    try:
        digest = verify(args.installer, args.signature)
    except Exception:
        parser.exit(1, 'Verification FAILED. Do not run the file. Check the filename and obtain fresh files from traceforge.space.\n')
    print('Signature and SHA-256 verified:', digest)
    print('This verifies release identity, not engineering correctness or Windows publisher reputation.')


if __name__ == '__main__':
    main()
