#!/usr/bin/env python3
"""Create and verify connected-release manifests and promotion signatures.

CI uses ``manifest`` to describe deterministic artifact and build inputs. A
trusted local operator uses ``keygen`` and ``promote`` after independently
checking the exact GitLab job, then ``verify`` gates the artifact before any
deployment mutation. OpenSSL is invoked with argument arrays and private key
contents are never read, logged, or emitted by this module. Commands perform
local file I/O and subprocesses only; callers must serialize writes to outputs.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
from typing import Any


SCHEMA_MANIFEST = "gss-connected-release-build-v1"
SCHEMA_PROMOTION = "gss-connected-release-promotion-v1"
BUILD_IMAGE = "python@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f"
BUILD_PLATFORM = "linux/amd64"
RUNTIME_IMAGE = "docker.io/library/python@sha256:f77ac9e44ae96ef2c90b8053ea08c31f8be030f824196b0ae4db6d462c84e51f"
RUNTIME_PLATFORM = "linux/arm64"
TARGET = "local-release-lab"
ARTIFACT_NAME = "release.pyz"
HEX_SHA = re.compile(r"[0-9a-f]{40}")


class ContractError(ValueError):
    """Report a malformed or mismatched release contract.

    Instances contain a non-secret explanation suitable for stderr. Creating
    the exception has no side effects and is deterministic.
    """


def sha256(path: Path) -> str:
    """Hash one local file without modifying it.

    Args:
        path: Existing readable regular file.

    Returns:
        Lowercase SHA-256 hexadecimal digest.

    Raises:
        OSError: If the file cannot be read.

    Side effects:
        Reads the file once. A concurrent writer can make the result unusable;
        callers must provide immutable inputs.
    """
    digest = hashlib.sha256()
    with path.open("rb") as stream:
        for block in iter(lambda: stream.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def canonical_bytes(value: dict[str, Any]) -> bytes:
    """Serialize a JSON object into the exact signed representation.

    Args:
        value: JSON-compatible object with string keys.

    Returns:
        UTF-8 JSON with sorted keys, compact separators, and one final newline.

    Raises:
        TypeError: If ``value`` is not JSON serializable.

    Side effects:
        None. Serialization is deterministic for the accepted JSON types.
    """
    return (json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n").encode()


def write_new(path: Path, content: bytes, mode: int = 0o644) -> None:
    """Create one evidence file without overwriting prior output.

    Args:
        path: New file path whose parent already exists.
        content: Exact bytes to persist.
        mode: Permission bits applied at creation.

    Returns:
        None.

    Raises:
        FileExistsError: If the path already exists.
        OSError: If creation or writing fails.

    Side effects:
        Creates and fsyncs one file. Concurrent creation is fail-closed through
        exclusive mode; there is no retry or replacement.
    """
    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
    with os.fdopen(descriptor, "wb") as stream:
        stream.write(content)
        stream.flush()
        os.fsync(stream.fileno())


def positive_id(value: str, name: str) -> int:
    """Parse a positive GitLab numeric identifier.

    Args:
        value: Decimal text received from a CLI or CI variable.
        name: Field label for a non-secret error.

    Returns:
        Positive integer.

    Raises:
        ContractError: If parsing fails or the number is not positive.

    Side effects:
        None; parsing is deterministic.
    """
    try:
        result = int(value)
    except (TypeError, ValueError) as error:
        raise ContractError(f"{name} must be a positive integer") from error
    if result <= 0:
        raise ContractError(f"{name} must be a positive integer")
    return result


def require_sha(value: str) -> str:
    """Validate one full lowercase Git commit SHA-1.

    Args:
        value: Candidate full commit identifier.

    Returns:
        The unchanged validated value.

    Raises:
        ContractError: If the identifier is not 40 lowercase hex characters.

    Side effects:
        None; validation is deterministic.
    """
    if not HEX_SHA.fullmatch(value):
        raise ContractError("source SHA must be 40 lowercase hexadecimal characters")
    return value


def required_environment(name: str) -> str:
    """Read a required non-secret CI identity variable.

    Args:
        name: Environment variable name.

    Returns:
        Non-empty variable value.

    Raises:
        ContractError: If the variable is unset or empty.

    Side effects:
        Reads process environment. It never enumerates or logs the environment.
    """
    value = os.environ.get(name, "")
    if not value:
        raise ContractError(f"required CI variable is missing: {name}")
    return value


def load_object(path: Path) -> tuple[dict[str, Any], bytes]:
    """Read one canonical JSON object and retain its exact bytes.

    Args:
        path: Existing UTF-8 JSON file.

    Returns:
        Parsed object and exact source bytes.

    Raises:
        OSError: If the file cannot be read.
        ContractError: If JSON is invalid, is not an object, or is not in the
            canonical representation produced by this tool.

    Side effects:
        Reads one local file. Callers must prevent concurrent modification.
    """
    raw = path.read_bytes()
    try:
        value = json.loads(raw)
    except json.JSONDecodeError as error:
        raise ContractError(f"invalid JSON: {path}") from error
    if not isinstance(value, dict) or canonical_bytes(value) != raw:
        raise ContractError(f"JSON is not a canonical object: {path}")
    return value, raw


def build_manifest(args: argparse.Namespace) -> dict[str, Any]:
    """Construct the CI build manifest from exact files and CI identities.

    Args:
        args: Parsed manifest paths. GitLab identity values are read from the
            documented CI variables rather than inferred from Git history.

    Returns:
        JSON-compatible build manifest.

    Raises:
        OSError: If an input file cannot be read.
        ContractError: If a CI identity or version violates the fixed contract.

    Side effects:
        Reads four local files and selected non-secret CI variables. It does not
        write files, call the network, or invoke Git.
    """
    version = args.version_file.read_text(encoding="utf-8").removesuffix("\n")
    if version not in {"known-good-a", "candidate-b"}:
        raise ContractError("unsupported release version")
    if args.artifact.name != ARTIFACT_NAME:
        raise ContractError(f"artifact must be named {ARTIFACT_NAME}")
    return {
        "schema": SCHEMA_MANIFEST,
        "project": {
            "id": positive_id(required_environment("CI_PROJECT_ID"), "project id"),
            "path": required_environment("CI_PROJECT_PATH"),
        },
        "source": {"sha": require_sha(required_environment("CI_COMMIT_SHA"))},
        "pipeline": {
            "id": positive_id(required_environment("CI_PIPELINE_ID"), "pipeline id"),
            "source": required_environment("CI_PIPELINE_SOURCE"),
            "ref": required_environment("CI_COMMIT_REF_NAME"),
        },
        "job": {
            "id": positive_id(required_environment("CI_JOB_ID"), "job id"),
            "name": required_environment("CI_JOB_NAME"),
            "runner_id": positive_id(required_environment("CI_RUNNER_ID"), "runner id"),
        },
        "inputs": {
            "builder_sha256": sha256(args.builder),
            "ci_sha256": sha256(args.ci_file),
            "version_file_sha256": sha256(args.version_file),
            "version": version,
            "command": [
                "python3", "build_fixture.py", "--version-file", "version.txt",
                "--output", "dist/release.pyz",
            ],
        },
        "artifact": {
            "name": ARTIFACT_NAME,
            "bytes": args.artifact.stat().st_size,
            "sha256": sha256(args.artifact),
        },
        "build": {"image": BUILD_IMAGE, "platform": BUILD_PLATFORM},
        "runtime": {"image": RUNTIME_IMAGE, "platform": RUNTIME_PLATFORM},
        "target": TARGET,
    }


def public_key_der(public_key: Path) -> bytes:
    """Convert an Ed25519 public key to DER for stable fingerprinting.

    Args:
        public_key: OpenSSL-readable PEM public key.

    Returns:
        DER SubjectPublicKeyInfo bytes.

    Raises:
        RuntimeError: If OpenSSL rejects the key.

    Side effects:
        Runs ``openssl pkey`` without network access or file writes.
    """
    result = subprocess.run(
        ["openssl", "pkey", "-pubin", "-in", str(public_key), "-outform", "DER"],
        check=False,
        capture_output=True,
    )
    if result.returncode != 0:
        raise RuntimeError("OpenSSL could not read the public key")
    return result.stdout


def key_fingerprint(public_key: Path) -> str:
    """Return the SHA-256 identity of an Ed25519 public key.

    Args:
        public_key: OpenSSL-readable PEM public key.

    Returns:
        Lowercase SHA-256 digest of DER SubjectPublicKeyInfo bytes.

    Raises:
        RuntimeError: If OpenSSL rejects the key.

    Side effects:
        Spawns one local OpenSSL process and reads the public key.
    """
    return hashlib.sha256(public_key_der(public_key)).hexdigest()


def create_keypair(private_key: Path, public_key: Path) -> str:
    """Create one local Ed25519 key pair without exposing private bytes.

    Args:
        private_key: New private-key path in an existing private directory.
        public_key: New public-key path.

    Returns:
        Public-key SHA-256 fingerprint.

    Raises:
        ContractError: If either output exists or the private-key directory is
            group/world accessible.
        RuntimeError: If OpenSSL key generation or derivation fails.

    Side effects:
        Creates two files and invokes OpenSSL twice. No overwrite or retry is
        attempted; callers own secure deletion after the exercise.
    """
    if private_key.exists() or public_key.exists():
        raise ContractError("refusing to overwrite a key path")
    directory_mode = stat.S_IMODE(private_key.parent.stat().st_mode)
    if directory_mode & 0o077:
        raise ContractError("private-key directory must not allow group/world access")
    generated = subprocess.run(
        ["openssl", "genpkey", "-algorithm", "ED25519", "-out", str(private_key)],
        check=False,
        capture_output=True,
    )
    if generated.returncode != 0:
        raise RuntimeError("OpenSSL key generation failed")
    private_key.chmod(0o600)
    derived = subprocess.run(
        ["openssl", "pkey", "-in", str(private_key), "-pubout", "-out", str(public_key)],
        check=False,
        capture_output=True,
    )
    if derived.returncode != 0:
        private_key.unlink(missing_ok=True)
        public_key.unlink(missing_ok=True)
        raise RuntimeError("OpenSSL public-key derivation failed")
    return key_fingerprint(public_key)


def validate_manifest(
    manifest: dict[str, Any], artifact: Path, expected: argparse.Namespace
) -> None:
    """Require the manifest and artifact to match operator-verified GitLab inputs.

    Args:
        manifest: Parsed canonical CI manifest.
        artifact: Downloaded zipapp from the exact job archive.
        expected: Operator-supplied project, source, pipeline, job, runner, ref,
            source type, job name, version, input files, runtime and target.

    Returns:
        None after every field and local digest matches.

    Raises:
        OSError: If a local input cannot be read.
        ContractError: On a missing, extra, malformed, or mismatched value.

    Side effects:
        Reads the artifact and three reviewed fixture files. It performs no
        mutation and is deterministic for immutable inputs.
    """
    expected_manifest = {
        "schema": SCHEMA_MANIFEST,
        "project": {"id": expected.project_id, "path": expected.project_path},
        "source": {"sha": expected.source_sha},
        "pipeline": {
            "id": expected.pipeline_id,
            "source": expected.pipeline_source,
            "ref": expected.ref,
        },
        "job": {
            "id": expected.job_id,
            "name": expected.job_name,
            "runner_id": expected.runner_id,
        },
        "inputs": {
            "builder_sha256": sha256(expected.builder),
            "ci_sha256": sha256(expected.ci_file),
            "version_file_sha256": sha256(expected.version_file),
            "version": expected.version,
            "command": [
                "python3", "build_fixture.py", "--version-file", "version.txt",
                "--output", "dist/release.pyz",
            ],
        },
        "artifact": {
            "name": ARTIFACT_NAME,
            "bytes": artifact.stat().st_size,
            "sha256": sha256(artifact),
        },
        "build": {"image": BUILD_IMAGE, "platform": BUILD_PLATFORM},
        "runtime": {"image": RUNTIME_IMAGE, "platform": RUNTIME_PLATFORM},
        "target": TARGET,
    }
    if manifest != expected_manifest:
        raise ContractError("build manifest differs from verified inputs or artifact")


def sign_file(private_key: Path, source: Path, signature: Path) -> None:
    """Sign exact file bytes with a protected Ed25519 private key.

    Args:
        private_key: Local PEM key with mode no broader than ``0600``.
        source: Immutable bytes to sign.
        signature: New signature output path.

    Returns:
        None.

    Raises:
        ContractError: If key permissions are broad or output exists.
        RuntimeError: If OpenSSL signing fails.

    Side effects:
        Runs OpenSSL and creates one signature file. No retry or overwrite is
        performed; the private key path is passed but its contents are not read.
    """
    if private_key.is_symlink() or stat.S_IMODE(private_key.stat().st_mode) & 0o077:
        raise ContractError("private key must be a non-symlink with mode 0600 or narrower")
    if signature.exists():
        raise ContractError("refusing to overwrite a signature")
    result = subprocess.run(
        [
            "openssl", "pkeyutl", "-sign", "-rawin", "-inkey", str(private_key),
            "-in", str(source), "-out", str(signature),
        ],
        check=False,
        capture_output=True,
    )
    if result.returncode != 0:
        signature.unlink(missing_ok=True)
        raise RuntimeError("OpenSSL signing failed")


def verify_signature(public_key: Path, source: Path, signature: Path) -> None:
    """Verify an Ed25519 signature over exact file bytes.

    Args:
        public_key: Trusted PEM public key.
        source: Exact signed file.
        signature: Detached Ed25519 signature.

    Returns:
        None when OpenSSL validates the signature.

    Raises:
        ContractError: If the signature is invalid for the trusted key.

    Side effects:
        Runs one local OpenSSL verification process. It writes nothing and does
        not retry, so immutable inputs yield deterministic classification.
    """
    result = subprocess.run(
        [
            "openssl", "pkeyutl", "-verify", "-rawin", "-pubin", "-inkey",
            str(public_key), "-in", str(source), "-sigfile", str(signature),
        ],
        check=False,
        capture_output=True,
    )
    if result.returncode != 0:
        raise ContractError("promotion signature is invalid for the trusted key")


def promotion_record(
    manifest: dict[str, Any], manifest_raw: bytes, fingerprint: str, release_id: str
) -> dict[str, Any]:
    """Bind a verified build manifest to one approved local promotion.

    Args:
        manifest: Exact validated build manifest.
        manifest_raw: Canonical bytes read for that manifest.
        fingerprint: Trusted release public-key fingerprint.
        release_id: Unique non-empty operator-selected release identifier.

    Returns:
        Canonicalizable promotion record containing all deployment inputs.

    Raises:
        ContractError: If the release ID is empty or contains whitespace.

    Side effects:
        None. Construction is deterministic for its inputs.
    """
    if not release_id or any(character.isspace() for character in release_id):
        raise ContractError("release id must be non-empty and contain no whitespace")
    return {
        "schema": SCHEMA_PROMOTION,
        "release_id": release_id,
        "decision": "approved",
        "target": TARGET,
        "signer_fingerprint_sha256": fingerprint,
        "manifest_sha256": hashlib.sha256(manifest_raw).hexdigest(),
        "project": manifest["project"],
        "source": manifest["source"],
        "pipeline": manifest["pipeline"],
        "job": manifest["job"],
        "inputs": manifest["inputs"],
        "artifact": manifest["artifact"],
        "build": manifest["build"],
        "runtime": manifest["runtime"],
    }


def expected_arguments(parser: argparse.ArgumentParser) -> None:
    """Add the shared operator-verified build identity arguments.

    Args:
        parser: ``promote`` or ``verify`` subcommand parser to mutate.

    Returns:
        None.

    Side effects:
        Registers CLI arguments on ``parser``. Call exactly once per parser;
        argparse rejects conflicting concurrent registration.
    """
    parser.add_argument("--project-id", type=int, required=True)
    parser.add_argument("--project-path", required=True)
    parser.add_argument("--source-sha", required=True)
    parser.add_argument("--pipeline-id", type=int, required=True)
    parser.add_argument("--pipeline-source", default="push")
    parser.add_argument("--ref", default="main")
    parser.add_argument("--job-id", type=int, required=True)
    parser.add_argument("--job-name", default="build_release_fixture")
    parser.add_argument("--runner-id", type=int, required=True)
    parser.add_argument("--version", choices=("known-good-a", "candidate-b"), required=True)
    parser.add_argument("--builder", type=Path, required=True)
    parser.add_argument("--ci-file", type=Path, required=True)
    parser.add_argument("--version-file", type=Path, required=True)


def parse_cli() -> argparse.Namespace:
    """Define and parse the four local release-tool subcommands.

    Returns:
        Parsed namespace with a ``command`` discriminator.

    Raises:
        SystemExit: For invalid or incomplete command-line input.

    Side effects:
        Reads process arguments only; argparse may write help/errors to stdio.
    """
    parser = argparse.ArgumentParser()
    commands = parser.add_subparsers(dest="command", required=True)
    manifest = commands.add_parser("manifest")
    manifest.add_argument("--artifact", type=Path, required=True)
    manifest.add_argument("--builder", type=Path, required=True)
    manifest.add_argument("--ci-file", type=Path, required=True)
    manifest.add_argument("--version-file", type=Path, required=True)
    manifest.add_argument("--output", type=Path, required=True)
    keygen = commands.add_parser("keygen")
    keygen.add_argument("--private-key", type=Path, required=True)
    keygen.add_argument("--public-key", type=Path, required=True)
    promote = commands.add_parser("promote")
    promote.add_argument("--manifest", type=Path, required=True)
    promote.add_argument("--artifact", type=Path, required=True)
    promote.add_argument("--private-key", type=Path, required=True)
    promote.add_argument("--public-key", type=Path, required=True)
    promote.add_argument("--release-id", required=True)
    promote.add_argument("--output", type=Path, required=True)
    promote.add_argument("--signature", type=Path, required=True)
    expected_arguments(promote)
    verify = commands.add_parser("verify")
    verify.add_argument("--manifest", type=Path, required=True)
    verify.add_argument("--artifact", type=Path, required=True)
    verify.add_argument("--attestation", type=Path, required=True)
    verify.add_argument("--signature", type=Path, required=True)
    verify.add_argument("--public-key", type=Path, required=True)
    verify.add_argument("--trusted-fingerprint", required=True)
    verify.add_argument("--release-id", required=True)
    expected_arguments(verify)
    return parser.parse_args()


def run(args: argparse.Namespace) -> dict[str, Any]:
    """Execute one manifest, key, promotion, or verification operation.

    Args:
        args: Namespace returned by :func:`parse_cli` or an equivalent test.

    Returns:
        Non-secret result summary suitable for JSON stdout.

    Raises:
        ContractError: For any identity, signature, canonicalization, permission,
            or digest mismatch.
        OSError: For local file failures.
        RuntimeError: For OpenSSL execution failures.

    Side effects:
        Depending on the command, creates a manifest, key pair, attestation and
        signature, or reads/verifies files. It never calls a network or Docker.
        Output creation is exclusive and no failed mutation is retried.
    """
    if args.command == "manifest":
        record = build_manifest(args)
        write_new(args.output, canonical_bytes(record))
        return {"manifest": str(args.output), "sha256": sha256(args.output)}
    if args.command == "keygen":
        fingerprint = create_keypair(args.private_key, args.public_key)
        return {"public_key": str(args.public_key), "fingerprint_sha256": fingerprint}

    args.source_sha = require_sha(args.source_sha)
    for field in ("project_id", "pipeline_id", "job_id", "runner_id"):
        if getattr(args, field) <= 0:
            raise ContractError(f"{field} must be positive")
    manifest, manifest_raw = load_object(args.manifest)
    validate_manifest(manifest, args.artifact, args)

    if args.command == "promote":
        fingerprint = key_fingerprint(args.public_key)
        attestation = promotion_record(manifest, manifest_raw, fingerprint, args.release_id)
        write_new(args.output, canonical_bytes(attestation))
        try:
            sign_file(args.private_key, args.output, args.signature)
            verify_signature(args.public_key, args.output, args.signature)
        except Exception:
            args.output.unlink(missing_ok=True)
            args.signature.unlink(missing_ok=True)
            raise
        return {
            "attestation": str(args.output),
            "attestation_sha256": sha256(args.output),
            "signature": str(args.signature),
            "signer_fingerprint_sha256": fingerprint,
        }

    fingerprint = key_fingerprint(args.public_key)
    if fingerprint != args.trusted_fingerprint:
        raise ContractError("public key does not match the trusted release fingerprint")
    attestation, _ = load_object(args.attestation)
    expected_attestation = promotion_record(
        manifest, manifest_raw, fingerprint, args.release_id
    )
    if attestation != expected_attestation:
        raise ContractError("promotion attestation differs from verified inputs")
    verify_signature(args.public_key, args.attestation, args.signature)
    return {
        "outcome": "verified",
        "artifact_sha256": manifest["artifact"]["sha256"],
        "release_id": args.release_id,
        "target": TARGET,
        "signer_fingerprint_sha256": fingerprint,
    }


def main() -> None:
    """Run one command and emit only its non-secret JSON summary.

    Inputs come from explicit paths/identities and selected CI variables.
    Successful commands print one JSON object. Expected failures propagate with
    a nonzero exit; no network, Docker, token, or secret output is involved.
    """
    print(json.dumps(run(parse_cli()), sort_keys=True))


if __name__ == "__main__":
    main()
