# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-hardware-key-attestation-that-is-cryptographically-valid-but-semantically-stale-at-the-aaif-trust-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-hardware-key-attestation-that-is-cryptographically-valid-but-semantically-stale-at-the-aaif-trust-boundary.warrant.json
# Markdown SHA-256:   7bc37130532f9098345d2b208bf8b3b55010fe0ed831f72e5412a0d5afc99bd6
# Code AST SHA-256:   3c5016ce357b6002887f02b375e9dbb0b6a5d8e122e5e319481afcddbe17c90c
# Verified Classes:   BindingContinuityError, Handoff
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class BindingContinuityError(RuntimeError):
    """Raised when fresh hardware attestation and stale credential name different keys."""
    pass


def thumbprint(public_key_der: bytes) -> str:
    return hashlib.sha256(public_key_der).hexdigest()


@dataclass(frozen=True)
class Handoff:
    quote_nonce: bytes
    quote_key_der: bytes          # key the fresh quote was produced under
    kac_key_der: bytes            # key bound by the key-attestation certificate
    credential_key_der: bytes     # key named inside the federated credential
    warrant_signer_der: bytes     # key that signed the delegation warrant
    expected_nonce: bytes


def verify_binding_continuity(h: Handoff) -> str:
    if h.quote_nonce != h.expected_nonce:
        raise BindingContinuityError(
            "quote nonce does not match transaction nonce; possible replay"
        )

    t_quote = thumbprint(h.quote_key_der)
    t_kac = thumbprint(h.kac_key_der)
    t_cred = thumbprint(h.credential_key_der)
    t_warrant = thumbprint(h.warrant_signer_der)

    if t_quote != t_kac:
        raise BindingContinuityError(
            f"quote key {t_quote[:12]} not attested by KAC key {t_kac[:12]}"
        )
    if t_quote != t_cred:
        raise BindingContinuityError(
            f"credential names stale key {t_cred[:12]}; "
            f"fresh attested key is {t_quote[:12]}; request reissue from issuer"
        )
    if t_quote != t_warrant:
        raise BindingContinuityError(
            f"warrant signed by {t_warrant[:12]} but presenter holds {t_quote[:12]}; "
            f"delegator rotated without re-signing"
        )
    return t_quote


def accept_handoff(h: Handoff) -> str:
    # All three per-layer checks (quote, KAC, credential) are assumed to have
    # already passed independently. This function enforces only the cross-layer
    # binding-continuity invariant that no single layer owns.
    return verify_binding_continuity(h)
