# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-hardware-backed-attestation-key-mid-handoff-and-the-verifiable-credential-s-subject-binding-silently-diverge.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-rotates-its-hardware-backed-attestation-key-mid-handoff-and-the-verifiable-credential-s-subject-binding-silently-diverge.warrant.json
# Markdown SHA-256:   b9c58a3ce290f20b7ecdc39c248deae3c07bf395eca255ae32cf39196342a730
# Code AST SHA-256:   9bfba5114846aa0719290e9295a2bbb50b14807b38de33efdab47c951a1b97ce
# Verified Classes:   AttestationSubjectDivergence, Credential, SignedMessage, TrustStore
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class AttestationSubjectDivergence(RuntimeError):
    """Raised when a credential's subject measurement no longer describes
    the live workload, or when a retained key signs past its rotation epoch."""
    pass


@dataclass
class Credential:
    subject_measurement: str      # launch digest the VC asserts
    signing_key_id: str
    issued_at: float
    expires_at: float


@dataclass
class SignedMessage:
    key_id: str
    signed_at: float
    live_measurement: str         # measurement of the running image at signing
    body: bytes


@dataclass
class TrustStore:
    trusted_keys: set
    rotation_epochs: dict         # key_id -> timestamp after which key is verify-only


def verify_handoff(
    cred: Credential,
    msg: SignedMessage,
    store: TrustStore,
    policy_allowed_measurements: set,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # 1. Key must be trusted at all.
    if msg.key_id not in store.trusted_keys:
        raise AttestationSubjectDivergence(
            f"key {msg.key_id} not in trust store"
        )

    # 2. Credential must not be expired.
    if now > cred.expires_at:
        raise AttestationSubjectDivergence(
            f"credential for {cred.signing_key_id} expired at {cred.expires_at}"
        )

    # 3. THE INVARIANT: a retained key may only verify signatures produced
    #    before its rotation epoch. Post-rotation signatures from a retained
    #    key are a silent subject divergence.
    epoch = store.rotation_epochs.get(msg.key_id)
    if epoch is not None and msg.signed_at > epoch:
        raise AttestationSubjectDivergence(
            f"key {msg.key_id} signed at {msg.signed_at} after rotation "
            f"epoch {epoch}; retained key cannot attest new state"
        )

    # 4. The credential's subject must match the LIVE measurement, not a
    #    cached one. If the VC was minted under an old image and the live
    #    image has moved, the subject no longer describes the signer.
    if cred.subject_measurement != msg.live_measurement:
        raise AttestationSubjectDivergence(
            f"credential subject {cred.subject_measurement} != live "
            f"measurement {msg.live_measurement}; workload continuity broken"
        )

    # 5. Live measurement must be policy-permitted.
    if msg.live_measurement not in policy_allowed_measurements:
        raise AttestationSubjectDivergence(
            f"live measurement {msg.live_measurement} not in policy set"
        )
    # Handoff accepted: key continuity AND workload continuity both hold.
