# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-federated-peer-s-identity-claim-after-the-trust-anchor-s-revocation-epoch-has-advanced-mid-handoff.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-federated-peer-s-identity-claim-after-the-trust-anchor-s-revocation-epoch-has-advanced-mid-handoff.warrant.json
# Markdown SHA-256:   1ba517c10a8193d86ea1984300a6ce8f727abd84a290783116840813e63f5e9a
# Code AST SHA-256:   ca210141605a171445ed4993d7e75f2f3ea55883964fee48c509295d1f64a7b3
# Verified Classes:   StaleEpochAuthorizationError, TrustAnchor, IdentityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class StaleEpochAuthorizationError(RuntimeError):
    """Raised when an identity token's epoch is older than the anchor's current epoch at authorization time."""
    pass


class TrustAnchor:
    def __init__(self, current_epoch: int):
        self.current_epoch = current_epoch

    def revoke(self):
        self.current_epoch += 1

    def fresh_epoch(self) -> int:
        # In production this is a network read; here it is the authoritative counter.
        return self.current_epoch


class IdentityToken:
    def __init__(self, peer_id: str, epoch: int, scope: str):
        self.peer_id = peer_id
        self.epoch = epoch
        self.scope = scope


def authorize(token: IdentityToken, anchor: TrustAnchor, requested_scope: str) -> str:
    """Authorize a peer action only if the token's epoch matches the anchor's fresh epoch."""
    fresh = anchor.fresh_epoch()
    if token.epoch < fresh:
        raise StaleEpochAuthorizationError(
            f"token epoch {token.epoch} is stale; anchor advanced to {fresh} "
            f"(peer={token.peer_id}, scope={requested_scope})"
        )
    if requested_scope not in token.scope:
        raise StaleEpochAuthorizationError(
            f"scope {requested_scope!r} not in token scope {token.scope!r}"
        )
    return f"authorized peer={token.peer_id} epoch={fresh} scope={requested_scope}"


def baton_pass(token: IdentityToken, anchor: TrustAnchor, requested_scope: str) -> str:
    # Revalidate at the handoff boundary, not at resolution time.
    return authorize(token, anchor, requested_scope)


if __name__ == "__main__":
    anchor = TrustAnchor(current_epoch=41)
    token = IdentityToken(peer_id="beta", epoch=41, scope="read,write")
    # Resolution-time check passes.
    assert authorize(token, anchor, "read").startswith("authorized")
    # Anchor revokes write scope mid-task.
    anchor.revoke()  # epoch -> 42
    try:
        baton_pass(token, anchor, "write")
    except StaleEpochAuthorizationError as exc:
        print(f"handoff rejected: {exc}")
