# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-capability-grant-whose-jurisdiction-tag-was-laundered-through-an-intermediate-agent-s-re-attestation.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-federated-capability-grant-whose-jurisdiction-tag-was-laundered-through-an-intermediate-agent-s-re-attestation.warrant.json
# Markdown SHA-256:   a6754e62b9335f230bdeaa3e10f48cabdeb16e189b9d493767f81ef9a95eae32
# Code AST SHA-256:   1db5bf68bf4358dc4d7a458ffd6c5fa4d1416897aa1b4713aa6db81b9f6cf98d
# Verified Classes:   ResidencyLaunderingError
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class ResidencyLaunderingError(RuntimeError):
    """Raised when a federated grant's residency tag is not bound to a
    signer whose registered jurisdiction satisfies that tag."""
    pass


def validate_federated_grant(grant: dict, executor_allowed: set[str],
                             jurisdiction_of: dict[str, str]) -> None:
    """Walk the delegation chain and enforce per-hop jurisdiction binding.

    grant = {
        "issuer": str,
        "residency": str,
        "delegated_from": dict | None,   # parent grant, recursively
    }
    """
    hop = grant
    seen = set()
    while hop is not None:
        issuer = hop["issuer"]
        if issuer in seen:
            raise ResidencyLaunderingError(
                f"delegation cycle detected at issuer {issuer!r}")
        seen.add(issuer)

        asserted = hop.get("residency")
        if asserted is None:
            raise ResidencyLaunderingError(
                f"grant from {issuer!r} carries no residency tag")

        signer_juris = jurisdiction_of.get(issuer)
        if signer_juris is None:
            raise ResidencyLaunderingError(
                f"issuer {issuer!r} has no registered jurisdiction")

        # The conjunct that re-attestation silently drops:
        # the signer must actually be allowed to assert this residency.
        if signer_juris != asserted and not signer_juris.startswith(asserted + ":"):
            raise ResidencyLaunderingError(
                f"residency laundering: issuer {issuer!r} is in "
                f"{signer_juris!r} but asserts residency {asserted!r}")

        hop = hop.get("delegated_from")

    # Only after the chain is proven authority-consistent do we check
    # the executor's own allow-list against the *root* assertion.
    root_asserted = grant["residency"]
    if root_asserted not in executor_allowed:
        raise ResidencyLaunderingError(
            f"executor does not accept residency {root_asserted!r}")
