# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-hardware-bound-attestation-key-that-silently-re-parents-across-a-tpm-clear-and-reseal.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-hardware-bound-attestation-key-that-silently-re-parents-across-a-tpm-clear-and-reseal.warrant.json
# Markdown SHA-256:   3340902f4a4779a07623a0eabb3e771cbbc1ae74adee7a66a58b50f237864425
# Code AST SHA-256:   a3c67f0cdc877548cfd0f58585ba185810c2555937113f0bf845e6398c181e77
# Verified Classes:   AttestationReparentingError, Quote
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationReparentingError(RuntimeError):
    """Raised when an agent's hardware attestation key has been re-parented
    to a different boot session while presenting the same agent ID and
    endorsement chain. Signature validity is intact; binding continuity is not."""


@dataclass(frozen=True)
class Quote:
    agent_id: str
    ak_pub: bytes
    endorsement_serial: str
    boot_session_nonce: bytes
    pcr_digest: bytes
    verifier_nonce: bytes
    signature_valid: bool


def ak_fingerprint(ak_pub: bytes) -> str:
    return hashlib.sha256(ak_pub).hexdigest()


def verify_handoff(
    quote: Quote,
    pinned_fingerprint: str | None,
    expected_verifier_nonce: bytes,
    last_boot_session_nonce: bytes | None,
    requires_attestation_continuity: bool,
) -> str:
    if not quote.signature_valid:
        raise AttestationReparentingError(
            f"signature invalid for {quote.agent_id}"
        )

    if quote.verifier_nonce != expected_verifier_nonce:
        raise AttestationReparentingError(
            f"stale or replayed quote for {quote.agent_id}: "
            f"verifier nonce mismatch"
        )

    current_fp = ak_fingerprint(quote.ak_pub)

    if not requires_attestation_continuity:
        return current_fp

    if pinned_fingerprint is None:
        raise AttestationReparentingError(
            f"no pinned AK fingerprint for {quote.agent_id}; "
            f"cannot prove continuity across handoff"
        )

    if current_fp != pinned_fingerprint:
        raise AttestationReparentingError(
            f"AK fingerprint changed for {quote.agent_id}: "
            f"pinned={pinned_fingerprint} current={current_fp} "
            f"(possible TPM clear-and-reseal re-parenting)"
        )

    if (
        last_boot_session_nonce is not None
        and quote.boot_session_nonce != last_boot_session_nonce
    ):
        raise AttestationReparentingError(
            f"boot-session nonce changed for {quote.agent_id} under "
            f"identical AK fingerprint; endorsement not session-scoped"
        )

    return current_fp
