# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-that-a-federated-peer-s-capability-grant-was-minted-against-a-stale-trust-epoch-and-why-does-the-signature-check-pass-an.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-that-a-federated-peer-s-capability-grant-was-minted-against-a-stale-trust-epoch-and-why-does-the-signature-check-pass-an.warrant.json
# Markdown SHA-256:   e078cd664976d5ff5d64e5834afcef4e349d76420b820e7242729e95b56d3d97
# Code AST SHA-256:   d1f8768fdf0d2205c957ba6751aee7a5bf64d6fa46a9f77f63c450a940e1b9e1
# Verified Classes:   StaleTrustEpochError, Grant, VerifierPolicy
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class StaleTrustEpochError(RuntimeError):
    """Raised when a grant's mint-epoch or reissue-depth violates the federation invariant."""


@dataclass(frozen=True)
class Grant:
    principal: str
    resource: str
    scope: str
    mint_epoch: int          # epoch under which the ORIGINAL authorization decision was made
    signing_epoch: int       # epoch under which THIS signature was produced
    reissue_depth: int       # how many rotations this grant has survived via re-sign
    signature_valid: bool


@dataclass(frozen=True)
class VerifierPolicy:
    current_epoch: int
    max_reissue_depth: int = 1
    max_mint_epoch_skew: int = 1   # mint_epoch may lag current_epoch by at most this


def verify_grant(grant: Grant, policy: VerifierPolicy) -> None:
    # 1. Signature must verify against the verifier's current anchor.
    if not grant.signature_valid:
        raise StaleTrustEpochError(
            f"signature does not verify for {grant.principal}->{grant.resource}"
        )

    # 2. Signing epoch must equal the verifier's current epoch. A grant signed
    #    under a superseded key is unverifiable and must be re-issued.
    if grant.signing_epoch != policy.current_epoch:
        raise StaleTrustEpochError(
            f"grant signed under epoch {grant.signing_epoch}, "
            f"verifier at epoch {policy.current_epoch}"
        )

    # 3. Mint-epoch must be within the bounded skew window. This is the check
    #    that catches the silent failure: a re-signed grant carrying a stale
    #    mint_epoch passes the signature check but fails here.
    skew = policy.current_epoch - grant.mint_epoch
    if skew < 0:
        raise StaleTrustEpochError(
            f"grant mint_epoch {grant.mint_epoch} is in the future "
            f"relative to verifier epoch {policy.current_epoch}"
        )
    if skew > policy.max_mint_epoch_skew:
        raise StaleTrustEpochError(
            f"grant mint_epoch {grant.mint_epoch} lags verifier epoch "
            f"{policy.current_epoch} by {skew} > {policy.max_mint_epoch_skew}; "
            f"authorization decision must be re-evaluated, not re-signed"
        )

    # 4. Re-issue depth must be bounded. This is the verifier-side check that
    #    survives a buggy broker re-issue path.
    if grant.reissue_depth > policy.max_reissue_depth:
        raise StaleTrustEpochError(
            f"grant reissue_depth {grant.reissue_depth} exceeds "
            f"federation max {policy.max_reissue_depth}"
        )


def broker_reissue(old: Grant, decision_valid: bool, new_epoch: int) -> Grant:
    """Broker re-issue path. Must refuse re-sign when the underlying
    authorization decision's validity window has expired."""
    if not decision_valid:
        raise StaleTrustEpochError(
            f"cannot re-sign grant for {old.principal}->{old.resource}: "
            f"authorization decision expired; re-mint required"
        )
    if old.reissue_depth + 1 > 1:
        raise StaleTrustEpochError(
            f"cannot re-sign grant for {old.principal}->{old.resource}: "
            f"reissue_depth would exceed federation bound"
        )
    return Grant(
        principal=old.principal,
        resource=old.resource,
        scope=old.scope,
        mint_epoch=old.mint_epoch,
        signing_epoch=new_epoch,
        reissue_depth=old.reissue_depth + 1,
        signature_valid=True,
    )
