# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-attest-its-capability-token-mid-handoff-rather-than-trust-the-delegation-chain.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-attest-its-capability-token-mid-handoff-rather-than-trust-the-delegation-chain.warrant.json
# Markdown SHA-256:   602ad80e2e1f02488b70c3a79f78d6b6b02100cf14deb5fe280a7c462aaccd54
# Code AST SHA-256:   a592f6ffc2c66fc0f1e7f5ecac52d903c8acc6ea6e5479d3ddf4bf373f0604fc
# Verified Classes:   FederationDepthExceeded, TrustRootNotAdmitted
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class FederationDepthExceeded(RuntimeError):
    """Raised when a delegation chain crosses more org boundaries than the
    receiver's own federation policy permits, regardless of token-asserted depth."""
    pass


class TrustRootNotAdmitted(RuntimeError):
    """Raised when an intermediate hop's issuer key is not in the receiver's
    federation trust store, even though the chain's root anchor is trusted."""
    pass


def verify_federated_chain(chain, receiver_trust_store, receiver_federation_policy):
    """
    chain: list of hops, each {issuer_org, issuer_key, grants, epoch}
    receiver_federation_policy: {"max_federation_depth": int}
    """
    if not chain:
        raise TrustRootNotAdmitted("empty delegation chain")

    root = chain[0]
    if root["issuer_key"] not in receiver_trust_store:
        raise TrustRootNotAdmitted(f"root issuer {root['issuer_org']} not admitted")

    fed_depth = 0
    prev = root
    for hop in chain[1:]:
        # Signature + attenuation checks assumed performed upstream.
        if hop["issuer_org"] != prev["issuer_org"]:
            fed_depth += 1
            if hop["issuer_key"] not in receiver_trust_store:
                raise TrustRootNotAdmitted(
                    f"cross-org hop {prev['issuer_org']}->{hop['issuer_org']} "
                    f"issuer key not in receiver trust store"
                )
            if hop["epoch"] < prev["epoch"]:
                raise TrustRootNotAdmitted(
                    f"stale federation admission at hop {hop['issuer_org']}"
                )
            if fed_depth > receiver_federation_policy["max_federation_depth"]:
                raise FederationDepthExceeded(
                    f"federation depth {fed_depth} exceeds receiver policy "
                    f"{receiver_federation_policy['max_federation_depth']}; "
                    f"token-asserted depth is NOT authoritative"
                )
        prev = hop

    return True
