# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-an-mcp-tool-grant-across-a-sub-agent-boundary-and-the-confused-deputy-guard-silently-collapses.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-an-mcp-tool-grant-across-a-sub-agent-boundary-and-the-confused-deputy-guard-silently-collapses.warrant.json
# Markdown SHA-256:   432950828eb83076fce79815a4024ef3fbf825d420dd59543c4a579696dffaf0
# Code AST SHA-256:   bcc6e02832fc33a85834a1a89286eac126f43a272f866c94b44fa9be04b72da2
# Verified Classes:   DelegationProvenanceError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class DelegationProvenanceError(RuntimeError):
    """Raised when a tool call's warrant is not bound to the calling instance
    or is not a proper descendant of the orchestrator's grant."""
    pass


def authorize_tool_call(
    caller_instance_id: str,
    requested_scope: str,
    presented_warrant: dict,
    orchestrator_warrant: dict,
) -> None:
    # (c) subject binding: the confused-deputy defense proper.
    if presented_warrant.get("subject") != caller_instance_id:
        raise DelegationProvenanceError(
            f"warrant subject {presented_warrant.get('subject')!r} does not match "
            f"calling instance {caller_instance_id!r}; refusing to act as deputy "
            f"on behalf of a principal that did not grant this instance."
        )

    # (b) scope containment.
    if not scope_contains(presented_warrant["scope"], requested_scope):
        raise DelegationProvenanceError(
            f"requested scope {requested_scope!r} not contained in warrant scope "
            f"{presented_warrant['scope']!r}."
        )

    # (d) least-privilege continuity: child warrant must be a descendant of the
    # orchestrator's warrant, never an ancestor or sibling.
    if not is_descendant_or_equal(presented_warrant, orchestrator_warrant):
        raise DelegationProvenanceError(
            f"warrant {presented_warrant.get('id')!r} is not a descendant of "
            f"orchestrator warrant {orchestrator_warrant.get('id')!r}; "
            f"instance {caller_instance_id!r} is presenting authority it was "
            f"never delegated."
        )


def dispatch_tool_call(caller_instance_id, requested_scope, presented_warrant,
                       orchestrator_warrant, transport):
    # No credential fallback: a denial is terminal for this instance.
    authorize_tool_call(
        caller_instance_id, requested_scope, presented_warrant, orchestrator_warrant
    )
    return transport.call(requested_scope, warrant=presented_warrant)


def scope_contains(granted: dict, requested: str) -> bool:
    tool, _, qualifier = requested.partition(":")
    allowed = granted.get(tool)
    if allowed is None:
        return False
    return qualifier == "" or qualifier in allowed


def is_descendant_or_equal(child: dict, ancestor: dict) -> bool:
    chain = child.get("chain", [])
    return any(link.get("id") == ancestor.get("id") for link in chain) or \
        child.get("id") == ancestor.get("id")
