# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-valid-oauth-token-for-the-wrong-resource-the-mcp-audience-binding-failure-at-tool-invocation-time.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-valid-oauth-token-for-the-wrong-resource-the-mcp-audience-binding-failure-at-tool-invocation-time.warrant.json
# Markdown SHA-256:   a6776efc4a9023d89996865965e4e7a0e55fb799d0b8a0d63b69749a7c75813b
# Code AST SHA-256:   a7fc6024a1186f7795adc228b079c94dba13665656930042b830d55ea8cb9519
# Verified Classes:   AudienceBindingError, Token, ToolPolicy, MCPAuthorizationGate
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class AudienceBindingError(RuntimeError):
    """Raised when a bearer token is valid but not a warrant for this resource/tool."""


@dataclass(frozen=True)
class Token:
    aud: str
    scope: FrozenSet[str]
    issuer: str
    exp: int


@dataclass(frozen=True)
class ToolPolicy:
    name: str
    required_scope: str


class MCPAuthorizationGate:
    def __init__(self, resource_id: str, trusted_issuer: str):
        self.resource_id = resource_id
        self.trusted_issuer = trusted_issuer

    def authorize(self, token: Token, tool: ToolPolicy, now: int) -> None:
        # Signature/expiry are assumed pre-verified upstream; this gate is the
        # per-call warrant check that per-tool scope alone does not provide.
        if token.exp <= now:
            raise AudienceBindingError(f"token expired at {token.exp}")

        if token.issuer != self.trusted_issuer:
            raise AudienceBindingError(
                f"issuer {token.issuer!r} not trusted by {self.resource_id!r}"
            )

        # The invariant: audience must name *this* resource, on *every* call.
        if token.aud != self.resource_id:
            raise AudienceBindingError(
                f"token audience {token.aud!r} does not bind to resource "
                f"{self.resource_id!r}; refusing tool {tool.name!r} "
                f"(confused-deputy: token was minted for another server)"
            )

        if tool.required_scope not in token.scope:
            raise AudienceBindingError(
                f"tool {tool.name!r} requires scope {tool.required_scope!r}; "
                f"token carries {sorted(token.scope)}"
            )


def handle_tools_call(
    gate: MCPAuthorizationGate,
    token: Token,
    tool: ToolPolicy,
    now: int,
) -> str:
    gate.authorize(token, tool, now)
    return f"executed {tool.name} under aud={token.aud}"
