# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-a-hardware-attested-agent-identity-whose-short-lived-verifiable-credential-expires-mid-handoff-the-attestation-freshness.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-a-hardware-attested-agent-identity-whose-short-lived-verifiable-credential-expires-mid-handoff-the-attestation-freshness.warrant.json
# Markdown SHA-256:   79c0e5f9a5ff3a14a02ebbd6c85c1cc2c104e8b0d46690d978bf36367edd6d39
# Code AST SHA-256:   3ea833c78459f0b61e36a550fa2312dd107f2601cc4be3c32955fbfca29bdbd4
# Verified Classes:   StaleAttestation, Credential, Lease
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAttestation(RuntimeError):
    """Raised when a hardware-attested VC is signature-valid but no longer
    vouches for the live holder or the current lease."""
    pass


@dataclass
class Credential:
    subject: str
    nbf: float
    exp: float
    baton_id: str
    measurement: str          # attestation quote measurement at mint time
    signature_valid: bool


@dataclass
class Lease:
    baton_id: str
    holder: str
    expires_at: float


def verify_handoff(
    cred: Credential,
    lease: Lease,
    live_measurement: str,
    baton_id: str,
    now: float,
    skew_tolerance: float = 0.0,
) -> None:
    # C1: never let skew widen the credential past the lease.
    accepted_start = cred.nbf - skew_tolerance
    accepted_end = cred.exp + skew_tolerance
    if not (accepted_start <= now <= accepted_end):
        raise StaleAttestation(
            f"credential outside accepted window at t={now:.1f}"
        )
    if accepted_end > lease.expires_at:
        raise StaleAttestation(
            "skew tolerance would extend authority past lease expiry; "
            f"accepted_end={accepted_end:.1f} lease_exp={lease.expires_at:.1f}"
        )

    # C2: signature validity is necessary, not sufficient.
    if not cred.signature_valid:
        raise StaleAttestation("signature invalid")

    # C3: baton must be bound into the credential.
    if cred.baton_id != baton_id or lease.baton_id != baton_id:
        raise StaleAttestation("baton not bound to credential/lease")

    # C2 continued: re-validate attestation against the live measurement.
    if cred.measurement != live_measurement:
        raise StaleAttestation(
            f"attestation measurement mismatch: minted={cred.measurement!r} "
            f"live={live_measurement!r}"
        )

    # Lease must still belong to this holder at verification time.
    if lease.holder != cred.subject:
        raise StaleAttestation(
            f"lease reassigned to {lease.holder!r}; {cred.subject!r} is stale"
        )
    if now > lease.expires_at:
        raise StaleAttestation("lease lapsed at receipt")


def handle_received_handoff(cred, lease, live_measurement, baton_id, now):
    try:
        verify_handoff(cred, lease, live_measurement, baton_id, now)
    except StaleAttestation:
        # Bounded recovery: request re-attestation under a fresh lease,
        # preserving the baton body. Do NOT cold-restart the worker.
        raise StaleAttestation(
            "handoff rejected; issue re-attestation request for baton "
            f"{baton_id!r} preserving execution state"
        )
    return "accepted"
