# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-warrant-whose-policy-digest-no-longer-matches-the-issuer-s-live-policy.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-federated-warrant-whose-policy-digest-no-longer-matches-the-issuer-s-live-policy.warrant.json
# Markdown SHA-256:   2b2fa22e9e041986534b1664446909b1e1093994bcd061ed1498f47d6da69da6
# Code AST SHA-256:   07c9b64da49399abd3eb07ae979c44ee44bdcba1fea844204ae0afb13a7a60c8
# Verified Classes:   StalePolicyWarrantError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class StalePolicyWarrantError(RuntimeError):
    """Raised when a federated warrant's policy epoch is behind the issuer's live epoch."""
    pass


def verify_federated_warrant(warrant: dict, issuer_state: dict) -> bool:
    """
    issuer_state: {"policy_epoch": int, "policy_digest": str, "reachable": bool}
    Invariant: a warrant is honored only if its signed policy_epoch >= the issuer's
    currently advertised epoch. Dereference is an audit, not a gate; the epoch is the gate.
    """
    if not _signature_valid(warrant):
        raise StalePolicyWarrantError("warrant signature invalid")

    if not issuer_state.get("reachable", False):
        # Fail-closed: cannot confirm epoch, so cannot confirm the grant.
        raise StalePolicyWarrantError(
            f"issuer {warrant['issuer']} unreachable; cannot confirm policy epoch"
        )

    live_epoch = issuer_state["policy_epoch"]
    warrant_epoch = warrant.get("policy_epoch")

    if warrant_epoch is None:
        # Legacy warrant with no epoch: treat as epoch 0, i.e. always stale.
        raise StalePolicyWarrantError(
            f"warrant from {warrant['issuer']} carries no policy_epoch; "
            f"cannot bound against live epoch {live_epoch}"
        )

    if warrant_epoch < live_epoch:
        raise StalePolicyWarrantError(
            f"warrant policy_epoch {warrant_epoch} < issuer live epoch {live_epoch}; "
            f"warrant minted under superseded policy (digest {warrant.get('policy_digest')})"
        )

    # Epoch is current. Digest dereference is deferred to background audit;
    # a mismatch there revokes the epoch, which the next call will catch.
    return True


def _signature_valid(warrant: dict) -> bool:
    return bool(warrant.get("sig"))
