# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-an-a2a-peer-whose-aaif-token-chains-to-a-valid-hardware-root-but-whose-attested-workload-digest-no-longer-matches-the-run.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-an-a2a-peer-whose-aaif-token-chains-to-a-valid-hardware-root-but-whose-attested-workload-digest-no-longer-matches-the-run.warrant.json
# Markdown SHA-256:   978e9d63aad9b17366b57f85ec77cf76a0ba0f6236a6d629d39a193e78afa2dc
# Code AST SHA-256:   8c877d992736a134eb1ed1852189dd86a9f4d34f5dc5c17a918420b77aa6315e
# Verified Classes:   WorkloadMeasurementMismatch, AAIFToken, LiveQuote
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class WorkloadMeasurementMismatch(RuntimeError):
    """Raised when a peer's live hardware quote does not bind to its AAIF workload claim."""
    pass


@dataclass(frozen=True)
class AAIFToken:
    sub: str
    kid: str
    wl_measure: str      # hex sha256 of attested workload
    exp: int
    signature_valid: bool


@dataclass(frozen=True)
class LiveQuote:
    kid: str
    measurement: str     # hex sha256 read from PCR / enclave at handshake time
    nonce: str
    quote_sig_valid: bool


def verify_peer_workload(
    token: AAIFToken,
    quote: LiveQuote,
    challenge_nonce: str,
    allow_list: dict[str, set[str]],
    now: int,
) -> None:
    # Structural checks first: cheap, unambiguous.
    if not token.signature_valid:
        raise WorkloadMeasurementMismatch(f"AAIF signature invalid for sub={token.sub}")
    if token.exp <= now:
        raise WorkloadMeasurementMismatch(f"AAIF token expired for sub={token.sub}")
    if token.kid != quote.kid:
        raise WorkloadMeasurementMismatch(
            f"key binding mismatch: token kid={token.kid} quote kid={quote.kid}"
        )

    # The invariant: live measurement must bind to the token's claim.
    if not quote.quote_sig_valid:
        raise WorkloadMeasurementMismatch("live hardware quote signature invalid")
    if quote.nonce != challenge_nonce:
        raise WorkloadMeasurementMismatch("quote nonce does not echo verifier challenge")
    if quote.measurement != token.wl_measure:
        raise WorkloadMeasurementMismatch(
            f"workload substitution: token claims {token.wl_measure[:12]}… "
            f"but live quote reads {quote.measurement[:12]}…"
        )

    # Allow-list check is per-sub and evaluated at handoff time, never cached as a decision.
    permitted = allow_list.get(token.sub, set())
    if quote.measurement not in permitted:
        raise WorkloadMeasurementMismatch(
            f"measurement {quote.measurement[:12]}… not allow-listed for sub={token.sub}"
        )


def handshake(
    token: AAIFToken,
    quote: LiveQuote,
    challenge_nonce: str,
    allow_list: dict[str, set[str]],
    now: int,
) -> str:
    verify_peer_workload(token, quote, challenge_nonce, allow_list, now)
    # Only after the invariant holds do we admit the peer to the swarm.
    return hashlib.sha256(f"{token.sub}:{quote.measurement}".encode()).hexdigest()
