# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-inbound-a2a-capability-grants-as-non-transitive-across-a-federation-gateway-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-inbound-a2a-capability-grants-as-non-transitive-across-a-federation-gateway-hop.warrant.json
# Markdown SHA-256:   ba7b0676834dd0085fcb161584f2bede87047166b54fd7fc0ad3dffe9e21054e
# Code AST SHA-256:   65a93255bd037e949c84b07c4caaeb14e25d9cd203d0b2e93f4f348a7a487401
# Verified Classes:   FederationProvenanceError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class FederationProvenanceError(RuntimeError):
    """Raised when an inbound A2A grant's delegation chain cannot be
    reconstructed to a trusted principal, or when a re-signing gateway
    has dropped delegation constraints."""
    pass


def admit_inbound_grant(grant: dict, trusted_principals: set[str],
                        gateway_id: str) -> bool:
    """
    Decide whether an inbound grant may be consumed AND whether it may be
    re-delegated downstream. Returns True only if the grant is authentic
    and its delegation chain is reconstructable to a trusted principal.
    Terminal grants (may_delegate=False or opaque chain) are admitted for
    consumption but marked non-transitive by the caller.
    """
    issuer = grant.get("issuer")
    chain = grant.get("delegation_chain", [])

    if issuer not in trusted_principals and issuer != gateway_id:
        raise FederationProvenanceError(
            f"grant issuer {issuer!r} is neither a trusted principal nor "
            f"the expected gateway {gateway_id!r}"
        )

    # Gateway re-signing hop: require a back-pointer to the original principal.
    if issuer == gateway_id:
        if not chain:
            raise FederationProvenanceError(
                "opaque grant: gateway re-signed with no delegation chain; "
                "cannot reconstruct principal, must treat as non-transitive"
            )
        root = chain[-1].get("issuer")
        if root not in trusted_principals:
            raise FederationProvenanceError(
                f"delegation chain terminates at {root!r}, not a trusted "
                f"principal; provenance laundering suspected"
            )
        # Delegation flag must survive translation verbatim.
        if "may_delegate" not in grant:
            raise FederationProvenanceError(
                "gateway dropped may_delegate flag during re-signing; "
                "refusing to infer transitivity"
            )
        # Depth check: chain length must not exceed any declared max.
        max_depth = grant.get("max_delegation_depth")
        if max_depth is not None and len(chain) > max_depth:
            raise FederationProvenanceError(
                f"delegation chain depth {len(chain)} exceeds declared "
                f"max {max_depth}"
            )

    return True


def re_delegate(grant: dict, target: str, trusted_principals: set[str],
                gateway_id: str) -> dict:
    """Attempt to re-delegate a grant to a downstream peer."""
    admit_inbound_grant(grant, trusted_principals, gateway_id)
    # Ordering invariant: delegation check BEFORE trust-anchor check.
    if not grant.get("may_delegate", False):
        raise FederationProvenanceError(
            f"grant from {grant.get('issuer')!r} is non-transitive; "
            f"refusing re-delegation to {target!r} without principal "
            f"authorization"
        )
    return {**grant, "subject": target,
            "delegation_chain": grant.get("delegation_chain", []) + [grant]}
