# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-mcp-oauth-token-whose-aud-matches-the-resource-server-but-whose-act-scope-chain-was-minted-for-a-differen.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-reject-an-mcp-oauth-token-whose-aud-matches-the-resource-server-but-whose-act-scope-chain-was-minted-for-a-differen.warrant.json
# Markdown SHA-256:   55f3e3e16cc2c6f954aedfa90d260b4136fc17dfbc5915eb7e0b41ba792d5f67
# Code AST SHA-256:   f49529e9a1802706893f08e8c9c6b4ecc6cc1e3ed97adbd9f84fb92add3566ce
# Verified Classes:   ConfusedDeputyError, Principal, ToolPolicy
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet, Optional, Tuple


class ConfusedDeputyError(RuntimeError):
    """Raised when a token is audience-valid but grant-invalid for the target tool."""


@dataclass(frozen=True)
class Principal:
    sub: str
    client_id: Optional[str]
    tenant: Optional[str]
    scope: FrozenSet[str]
    act_chain: Tuple[str, ...]


@dataclass(frozen=True)
class ToolPolicy:
    name: str
    tenant: str
    allowed_clients: FrozenSet[str]
    required_scope: FrozenSet[str]


def authorize_invocation(
    principal: Principal,
    token_aud: str,
    expected_aud: str,
    tool: ToolPolicy,
) -> None:
    # Envelope check: audience binding (RFC 8707). Necessary, not sufficient.
    if token_aud != expected_aud:
        raise ConfusedDeputyError(
            f"audience mismatch: token aud={token_aud!r} != resource {expected_aud!r}"
        )

    # Grant check: the deputy must know which principal delegated the call.
    if principal.client_id is None:
        raise ConfusedDeputyError(
            f"token for sub={principal.sub!r} lacks client_id; "
            f"cannot bind delegation for multi-client server"
        )
    if principal.client_id not in tool.allowed_clients:
        raise ConfusedDeputyError(
            f"client {principal.client_id!r} not authorized for tool {tool.name!r}; "
            f"audience matched but grant did not"
        )

    # Tenant binding: aud does not encode tenant; the claim must.
    if principal.tenant != tool.tenant:
        raise ConfusedDeputyError(
            f"tenant {principal.tenant!r} != tool tenant {tool.tenant!r} for {tool.name!r}"
        )

    # Scope membership.
    missing = tool.required_scope - principal.scope
    if missing:
        raise ConfusedDeputyError(
            f"tool {tool.name!r} requires scope {sorted(missing)}; token lacks it"
        )

    # Actor chain: any actor in the exchange chain must be authorized for the tool.
    for actor in principal.act_chain:
        if actor not in tool.allowed_clients:
            raise ConfusedDeputyError(
                f"actor {actor!r} in act chain not authorized for tool {tool.name!r}; "
                f"confused-deputy indicator despite valid aud"
            )
