# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-refuse-to-re-attest-after-a-hardware-key-rotation-mid-warrant-in-aaif.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-refuse-to-re-attest-after-a-hardware-key-rotation-mid-warrant-in-aaif.warrant.json
# Markdown SHA-256:   47789a6d24abd5a800e0d9d3416c0d4682f458c2b0c5f3cba2b3fab43e2f3b26
# Code AST SHA-256:   6ceaaea1355290cd0183a1458fc7769e7b2ee48fa43c1752676f8839b1badcd8
# Verified Classes:   WarrantEpochMismatch, Quote, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass
from typing import Optional


class WarrantEpochMismatch(RuntimeError):
    """Raised when an attestation quote cannot be bound to the presented warrant."""
    pass


@dataclass
class Quote:
    pubkey: bytes
    measurement: bytes
    nonce: bytes
    issued_at: float


@dataclass
class Warrant:
    cnf_jkt: bytes          # SHA-256 of bound public key at issuance
    iat_measurement: bytes  # measurement set recorded at issuance
    expires_at: float
    issuer_sig_valid: bool


def verify_composite(
    warrant: Warrant,
    quote: Quote,
    now: float,
    nonce_window_s: float = 30.0,
    expected_nonce: Optional[bytes] = None,
) -> bool:
    if not warrant.issuer_sig_valid:
        raise WarrantEpochMismatch("warrant signature does not chain to issuer")
    if now >= warrant.expires_at:
        raise WarrantEpochMismatch("warrant expired")

    # Invariant 1: key binding, not mere signature validity.
    if hashlib.sha256(quote.pubkey).digest() != warrant.cnf_jkt:
        raise WarrantEpochMismatch(
            "quote key does not match warrant cnf.jkt — rotation laundering attempt"
        )

    # Invariant 2: measurement epoch must be unchanged.
    if quote.measurement != warrant.iat_measurement:
        raise WarrantEpochMismatch(
            "measurement set changed since warrant issuance — epoch mismatch"
        )

    # Invariant 3: freshness, prevents stapling a pre-rotation quote.
    if now - quote.issued_at > nonce_window_s:
        raise WarrantEpochMismatch("attestation quote stale beyond replay window")
    if expected_nonce is not None and quote.nonce != expected_nonce:
        raise WarrantEpochMismatch("quote nonce does not match challenge")

    return True
