# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-identity-attestation-succeed-while-continuous-posture-binding-fails-silently-in-aaif-flows.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-identity-attestation-succeed-while-continuous-posture-binding-fails-silently-in-aaif-flows.warrant.json
# Markdown SHA-256:   c27b69564d0a7ed15699edd816f2f9db97253e2285ba1378594100317dd4e9d8
# Code AST SHA-256:   f9cf6fe7700501bfeed3af86d112572870dfbd0d0f69041d2af25b23187655c1
# Verified Classes:   PostureBindingError, PostureAssertion, VerifierState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class PostureBindingError(RuntimeError):
    """Raised when a posture assertion is validly signed but not freshly bound."""


@dataclass
class PostureAssertion:
    nonce: str
    posture_hash: str
    identity_key_id: str
    issued_at: float
    signature_valid: bool = True


@dataclass
class VerifierState:
    identity_cache: dict = field(default_factory=dict)
    identity_cache_ttl: float = 8 * 3600.0
    pat_interval: float = 30.0
    max_static_cycles: int = 3
    last_posture_hash: dict = field(default_factory=dict)
    static_cycles: dict = field(default_factory=dict)


def verify_pat(state: VerifierState, assertion: PostureAssertion, expected_nonce: str) -> None:
    # Identity attestation is cacheable; posture is not. A warm identity cache
    # must never substitute for a fresh posture binding.
    if not assertion.signature_valid:
        raise PostureBindingError(
            f"signature invalid for key {assertion.identity_key_id}"
        )

    if assertion.nonce != expected_nonce:
        raise PostureBindingError(
            "nonce mismatch: posture assertion is a replay, not a fresh binding"
        )

    now = time.time()
    cached = state.identity_cache.get(assertion.identity_key_id)
    if cached is not None and (now - cached) > state.identity_cache_ttl:
        # Cache expired: force a re-quote. This is the only path that would
        # have caught the observed drift, and it must not be the sole detector.
        state.identity_cache.pop(assertion.identity_key_id, None)

    prev = state.last_posture_hash.get(assertion.identity_key_id)
    if prev == assertion.posture_hash:
        state.static_cycles[assertion.identity_key_id] = (
            state.static_cycles.get(assertion.identity_key_id, 0) + 1
        )
        if state.static_cycles[assertion.identity_key_id] > state.max_static_cycles:
            raise PostureBindingError(
                f"posture hash {assertion.posture_hash[:12]} unchanged for "
                f"{state.static_cycles[assertion.identity_key_id]} cycles; "
                "collector likely serving a stale snapshot"
            )
    else:
        state.static_cycles[assertion.identity_key_id] = 0

    state.last_posture_hash[assertion.identity_key_id] = assertion.posture_hash
    state.identity_cache.setdefault(assertion.identity_key_id, now)
