# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-hardware-rooted-attestation-quote-expires-mid-session-and-the-agent-keeps-operating-on-a-stale-identity-binding.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-hardware-rooted-attestation-quote-expires-mid-session-and-the-agent-keeps-operating-on-a-stale-identity-binding.warrant.json
# Markdown SHA-256:   375173bb13f409fbbf3fff472086274fdd8dd060e06d84062e0e60c6290ae4d0
# Code AST SHA-256:   c7e97bfbcaf00b7ca98c32984395ba2d7dfc959125c19affdc6bbd843a63c37c
# Verified Classes:   StaleAttestationError, Quote, Warrant
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleAttestationError(RuntimeError):
    """Raised when an agent presents a warrant whose hardware attestation
    is no longer fresh, nonce-bound, or chained to the current host AK."""


@dataclass(frozen=True)
class Quote:
    nonce: bytes
    attested_at: float      # t_n, from TPM clock, verifier-cross-checked
    ak_fingerprint: str     # AK the quote chains to
    raw: bytes


@dataclass(frozen=True)
class Warrant:
    subject: str
    exp: float
    ak_fingerprint: str     # AK the warrant was issued against


FRESHNESS_CEILING_S = 20 * 60   # F: max tolerated quote age


def admit_agent(
    warrant: Warrant,
    quote: Quote,
    expected_nonce: bytes,
    current_host_ak: str,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # 1. Credential validity is necessary but NOT sufficient.
    if now >= warrant.exp:
        raise StaleAttestationError(
            f"warrant for {warrant.subject} expired at {warrant.exp}"
        )

    # 2. Verifier-chosen nonce: the agent cannot attest to its own freshness.
    if quote.nonce != expected_nonce:
        raise StaleAttestationError(
            "quote is not bound to the verifier-issued nonce (possible replay)"
        )

    # 3. Freshness ceiling, evaluated by the verifier from t_n, not agent time.
    age = now - quote.attested_at
    if age > FRESHNESS_CEILING_S:
        raise StaleAttestationError(
            f"attestation age {age:.0f}s exceeds ceiling "
            f"{FRESHNESS_CEILING_S}s; agent identity binding is stale"
        )

    # 4. Binding must chain to the AK of the host the agent runs on NOW,
    #    not the AK cached from a prior host (suspend/resume migration).
    if quote.ak_fingerprint != current_host_ak:
        raise StaleAttestationError(
            f"quote AK {quote.ak_fingerprint} != current host AK "
            f"{current_host_ak}; stale binding after migration"
        )
    if warrant.ak_fingerprint != current_host_ak:
        raise StaleAttestationError(
            "warrant was issued against a different hardware root of trust"
        )


def reattestation_tick(
    last_attested: float,
    quote_ok: bool,
    now: float | None = None,
) -> float:
    """Fail-closed re-attestation step. A failed quote must NOT leave the
    agent silently serving on a previous timestamp."""
    now = time.time() if now is None else now
    if not quote_ok:
        raise StaleAttestationError(
            "TPM2_Quote failed (retry/lockout); agent must enter DEGRADED "
            "and refuse new handoffs rather than continue on last-known-good"
        )
    return now
