# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-aaif-token-whose-pairwise-attestation-chain-is-valid-but-whose-scope-ceiling-was-minted-agai.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-aaif-token-whose-pairwise-attestation-chain-is-valid-but-whose-scope-ceiling-was-minted-agai.warrant.json
# Markdown SHA-256:   951d7ccf2dbd30d9fc70921e949d8a2886156a902894dabbede1efd97b500f20
# Code AST SHA-256:   14d574055841ae1e3062ef509cb8e73bf43c2666c03d578e6b94a22b070bb52d
# Verified Classes:   AuthorityEpochUnresolvableError
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AuthorityEpochUnresolvableError(RuntimeError):
    """Raised when a token's scope ceiling cannot be bound to a verifiable
    authority epoch for its signing key at mint time."""


def verify_federated_token(token, keyset, authority_registry, current_authority_view):
    key = keyset.get(token.signing_key_id)
    if key is None or key.status == "hard-revoked":
        raise AuthorityEpochUnresolvableError(
            f"signing key {token.signing_key_id} absent or hard-revoked"
        )

    # Signature and pairwise attestation chain are checked independently and
    # are presumed valid here; they do NOT establish scope authority.
    if not token.attestation_chain_verifies():
        raise AuthorityEpochUnresolvableError("attestation chain failed")

    # Resolve the authority the signing key held at the token's mint instant.
    epoch_authority = authority_registry.authority_at(
        key_id=token.signing_key_id, instant=token.iat
    )
    if epoch_authority is None:
        # Key is still valid-for-existing-signatures, but the per-epoch
        # authority record was pruned during rotation. We cannot prove the
        # declared ceiling was ever legitimate.
        current = current_authority_view.get(token.issuer_org, default=None)
        if current is None or token.declared_ceiling > current:
            raise AuthorityEpochUnresolvableError(
                f"epoch authority for {token.signing_key_id}@{token.iat} "
                f"unresolvable and declared ceiling {token.declared_ceiling} "
                f"exceeds current view {current}; refusing stale-authority fallback"
            )
        # Declared ceiling is within current authority; safe to admit.
        return Admission(granted=token.declared_ceiling, epoch="current-fallback")

    if token.declared_ceiling > epoch_authority:
        raise AuthorityEpochUnresolvableError(
            f"declared ceiling {token.declared_ceiling} exceeds authority "
            f"{epoch_authority} held by {token.signing_key_id} at {token.iat}"
        )

    return Admission(granted=token.declared_ceiling, epoch=token.iat)
