# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-posture-attestation-regression-when-its-hardware-backed-identity-key-outlives-the-tpm-quote-it-was-bound-to.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-posture-attestation-regression-when-its-hardware-backed-identity-key-outlives-the-tpm-quote-it-was-bound-to.warrant.json
# Markdown SHA-256:   3750a91387fa52be9e194ec198b3396f811eff4abc24479d32cca709cd13eda8
# Code AST SHA-256:   5d6a05556f1297cb5d8dc6b88a1345aa2b439ab0b101408cab4f354fecadcf9c
# Verified Classes:   PostureEpochMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class PostureEpochMismatch(RuntimeError):
    """Raised when an attestation's posture quote does not describe the boot
    epoch under which the identity signature was produced, or regresses
    behind the last observed epoch for the enrollment."""
    pass


def admit_request(
    enrollment_id: str,
    identity_sig_epoch: int,
    quote: dict,                  # {"boot_epoch": int, "pcr_digest": str, "nonce": str}
    request_nonce: str,
    policy_store: dict,           # epoch -> expected pcr_digest
    last_observed_epoch: dict,    # enrollment_id -> int
    nonce_cache: dict,            # nonce -> {"epoch": int, "digest": str}
) -> bool:
    # 1. nonce freshness (single-use)
    if quote["nonce"] != request_nonce or request_nonce in nonce_cache:
        return False

    # 2. epoch consistency across identity signature and quote
    if quote["boot_epoch"] != identity_sig_epoch:
        raise PostureEpochMismatch(
            f"{enrollment_id}: identity signed under epoch {identity_sig_epoch} "
            f"but quote attests epoch {quote['boot_epoch']}"
        )

    # 3. monotonic epoch: reject regression (replay of an older boot's posture)
    prior = last_observed_epoch.get(enrollment_id)
    if prior is not None and quote["boot_epoch"] < prior:
        raise PostureEpochMismatch(
            f"{enrollment_id}: quote epoch {quote['boot_epoch']} regresses "
            f"behind last observed {prior}"
        )

    # 4. policy check MUST be same-epoch; no cross-epoch grace comparison
    expected = policy_store.get(quote["boot_epoch"])
    if expected is None:
        raise PostureEpochMismatch(
            f"{enrollment_id}: no policy snapshot for epoch {quote['boot_epoch']}"
        )
    if quote["pcr_digest"] != expected:
        return False

    # 5. commit: advance epoch, consume nonce
    last_observed_epoch[enrollment_id] = quote["boot_epoch"]
    nonce_cache[request_nonce] = {
        "epoch": quote["boot_epoch"],
        "digest": quote["pcr_digest"],
    }
    return True
