# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-hardware-attestation-quote-expires-mid-handoff-ttl-skew-and-nonce-binding-failure-in-cross-org-a2a-trust.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-hardware-attestation-quote-expires-mid-handoff-ttl-skew-and-nonce-binding-failure-in-cross-org-a2a-trust.warrant.json
# Markdown SHA-256:   55ad3799c90f207f026706ad5cb61977283cd9cd8e1ff4593f6c0ffa50582948
# Code AST SHA-256:   b578caef2ce9e8e03d333082e241d5bd7acb37bd67333dbaeef8a278abe7805e
# Verified Classes:   AttestationBoundaryError, Quote, PlatformState
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass
from typing import Optional


class AttestationBoundaryError(RuntimeError):
    """Raised when a hardware attestation quote is consumed at a trust
    boundary it was not minted for, or by an instance whose platform
    identity diverged from the quote's bound key."""
    pass


@dataclass(frozen=True)
class Quote:
    ak_fingerprint: str          # hash of the attestation key public area
    measurement: str             # platform/image digest
    nonce: str                   # nonce the quote is bound to
    minted_at: float             # wall clock at mint
    reset_count: int             # TPM resetCount at mint
    restart_count: int           # TPM restartCount at mint
    signature: str               # over the above fields


@dataclass(frozen=True)
class PlatformState:
    ak_fingerprint: str
    reset_count: int
    restart_count: int
    measurement: str


def verify_at_boundary(
    quote: Quote,
    *,
    verifier_issued_nonce: Optional[str],
    verifier_clock: float,
    max_age_s: float,
    live_platform: PlatformState,
    allow_forwarded_as_evidence: bool = False,
) -> str:
    """Verify a quote at an org boundary.

    Returns 'live' if the quote is a point-of-use liveness proof,
    'evidence' if it is a forwarded historical assertion (capability-
    limited), and raises AttestationBoundaryError otherwise.
    """
    # 1. Platform identity divergence: the presenting instance is not the
    #    instance the quote was minted for (e.g. post-reschedule).
    if (
        quote.ak_fingerprint != live_platform.ak_fingerprint
        or quote.reset_count != live_platform.reset_count
        or quote.restart_count != live_platform.restart_count
    ):
        raise AttestationBoundaryError(
            "presenting platform diverged from quote-bound key: "
            f"quote_ak={quote.ak_fingerprint[:12]} "
            f"live_ak={live_platform.ak_fingerprint[:12]} "
            f"reset {quote.reset_count}->{live_platform.reset_count} "
            f"restart {quote.restart_count}->{live_platform.restart_count}"
        )

    # 2. Measurement must match what the quote attests.
    if quote.measurement != live_platform.measurement:
        raise AttestationBoundaryError(
            f"measurement mismatch: quote={quote.measurement[:12]} "
            f"live={live_platform.measurement[:12]}"
        )

    # 3. Expiry, evaluated against the CONSUMER's clock, not the minter's.
    age = verifier_clock - quote.minted_at
    if age < 0:
        raise AttestationBoundaryError(
            f"quote minted in the future (clock skew): age={age:.1f}s"
        )
    if age > max_age_s:
        raise AttestationBoundaryError(
            f"quote expired at this boundary: age={age:.1f}s > {max_age_s}s"
        )

    # 4. Nonce binding. A quote bound to a nonce this verifier did not
    #    issue is a forwarded assertion, not a liveness proof.
    if verifier_issued_nonce is None or quote.nonce != verifier_issued_nonce:
        if not allow_forwarded_as_evidence:
            raise AttestationBoundaryError(
                "forwarded quote: nonce not issued by this verifier "
                f"(quote_nonce={quote.nonce[:8]}, "
                f"verifier_nonce={(verifier_issued_nonce or 'none')[:8]}); "
                "re-challenge required before capability grant"
            )
        return "evidence"

    return "live"


def resume_from_checkpoint(
    blob: dict,
    live_platform: PlatformState,
    verifier_clock: float,
    max_age_s: float,
) -> dict:
    """Resume a checkpointed agent. Any quote carried in the blob must be
    scrubbed if the platform identity changed across the resume."""
    carried: Optional[Quote] = blob.get("agent_card", {}).get("attestation")
    if carried is not None:
        try:
            verify_at_boundary(
                carried,
                verifier_issued_nonce=None,
                verifier_clock=verifier_clock,
                max_age_s=max_age_s,
                live_platform=live_platform,
                allow_forwarded_as_evidence=False,
            )
        except AttestationBoundaryError as e:
            # Correct behavior: drop the stale quote, force re-attestation.
            blob["agent_card"].pop("attestation", None)
            blob["requires_reattestation"] = True
            blob.setdefault("resume_notes", []).append(str(e))
            return blob
    return blob


def fingerprint(public_area: bytes) -> str:
    return hashlib.sha256(public_area).hexdigest()
