# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-s-hardware-backed-attestation-key-survives-a-posture-downgrade-the-stale-warrant-continuity-gap-in-federated-agent-ident.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-s-hardware-backed-attestation-key-survives-a-posture-downgrade-the-stale-warrant-continuity-gap-in-federated-agent-ident.warrant.json
# Markdown SHA-256:   34f2ac07960d2f372d4d9756b7fed0c526e3c6e2db9d00bf0f161cfab0fda22c
# Code AST SHA-256:   65aedf98fbf7b7dbc49ba1e192c3c9e09764f84b7b7882743aaec55d8a841eb5
# Verified Classes:   StaleWarrantError, Enrollment, Attestation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass


class StaleWarrantError(RuntimeError):
    """Raised when a hardware attestation is cryptographically valid but its
    posture epoch is not confirmed-current within the freshness TTL."""


@dataclass(frozen=True)
class Enrollment:
    key_id: str
    posture_epoch: int
    enrolled_at: float


@dataclass(frozen=True)
class Attestation:
    key_id: str
    posture_epoch: int
    posture_digest: str
    signature_valid: bool
    heartbeat_ts: float


POSTURE_TTL_S = 90.0


def verify_warrant(
    att: Attestation,
    enroll: Enrollment,
    confirmed_epoch: int,
    now: float | None = None,
) -> None:
    now = time.time() if now is None else now

    # Signature check alone is the trap: it passes during warrant decay.
    if not att.signature_valid:
        raise StaleWarrantError(f"bad signature for key {att.key_id}")

    if att.key_id != enroll.key_id:
        raise StaleWarrantError(
            f"attestation key {att.key_id} does not match enrolled {enroll.key_id}"
        )

    # Invariant 1: posture epoch must be independently confirmed current.
    # A changed epoch means posture transitioned since enrollment; the
    # verifier must not accept the old binding until it re-confirms.
    if att.posture_epoch != confirmed_epoch:
        raise StaleWarrantError(
            f"posture epoch {att.posture_epoch} != confirmed {confirmed_epoch} "
            f"for key {att.key_id}; re-quote required before privileged call"
        )

    # Invariant 2: heartbeat freshness bounded by TTL.
    age = now - att.heartbeat_ts
    if age > POSTURE_TTL_S:
        raise StaleWarrantError(
            f"posture heartbeat age {age:.1f}s exceeds TTL {POSTURE_TTL_S}s "
            f"for key {att.key_id}"
        )
    # Warrant is fresh and posture-current; caller may proceed.
