# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hardware-attested-posture-as-a-perishable-lease-rather-than-a-durable-identity-claim-during-aaif-enrollment.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-hardware-attested-posture-as-a-perishable-lease-rather-than-a-durable-identity-claim-during-aaif-enrollment.warrant.json
# Markdown SHA-256:   447f63e594bc6a713bf0d4633a6da5b108c3d6a86e0efd3c8e171eba1dd1d515
# Code AST SHA-256:   f22a565740ba9705b6ea7be0a876d95141c9b2d0d0bf8369d6912b0ed7763fa1
# Verified Classes:   PostureLeaseExpired, PostureDurabilityViolation, AttestationBundle, FederationCredential
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass, field
from typing import Optional


class PostureLeaseExpired(RuntimeError):
    """Raised when a federation credential's posture lease has lapsed or been invalidated."""
    pass


class PostureDurabilityViolation(RuntimeError):
    """Raised when a credential's TTL exceeds its posture lease, conflating durable identity with perishable posture."""
    pass


@dataclass
class AttestationBundle:
    identity_key_fingerprint: str
    posture_measured_at: float          # epoch seconds of last successful quote
    posture_pcr_digest: str
    posture_policy_max_age: float       # seconds; e.g. 300


@dataclass
class FederationCredential:
    identity_key_fingerprint: str
    minted_at: float
    key_ttl: float                      # e.g. 86400
    posture_lease_expires_at: float
    posture_epoch: int
    suspended: bool = False


def mint_credential(bundle: AttestationBundle, now: Optional[float] = None) -> FederationCredential:
    now = now if now is not None else time.time()
    posture_lease_expires_at = bundle.posture_measured_at + bundle.posture_policy_max_age
    if posture_lease_expires_at <= now:
        raise PostureLeaseExpired(
            f"posture measured at {bundle.posture_measured_at} already exceeds "
            f"max_age {bundle.posture_policy_max_age}s at mint time {now}"
        )
    return FederationCredential(
        identity_key_fingerprint=bundle.identity_key_fingerprint,
        minted_at=now,
        key_ttl=86400.0,
        posture_lease_expires_at=posture_lease_expires_at,
        posture_epoch=0,
    )


def admit_call(cred: FederationCredential, now: Optional[float] = None) -> None:
    now = now if now is not None else time.time()
    if cred.suspended:
        raise PostureLeaseExpired("credential suspended by posture-change event")
    if now >= cred.posture_lease_expires_at:
        raise PostureLeaseExpired(
            f"posture lease expired at {cred.posture_lease_expires_at}, now {now}; "
            f"identity key {cred.identity_key_fingerprint} remains valid but posture is stale"
        )
    if now >= cred.minted_at + cred.key_ttl:
        raise PostureLeaseExpired("identity key TTL expired")


def on_posture_event(cred: FederationCredential, event: str) -> None:
    """Called when host reports PCR drift, unsigned module load, or integrity anomaly."""
    if event in ("pcr_drift", "unsigned_module", "integrity_anomaly", "firmware_counter_change"):
        cred.suspended = True
        cred.posture_epoch += 1


def assert_ttl_bound(cred: FederationCredential) -> None:
    """Guardrail: credential TTL must never exceed posture lease lifetime."""
    key_expiry = cred.minted_at + cred.key_ttl
    if cred.posture_lease_expires_at > key_expiry + 1e-9:
        raise PostureDurabilityViolation(
            f"posture lease {cred.posture_lease_expires_at} exceeds key expiry {key_expiry}; "
            f"credential would vouch for stale posture"
        )
