# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-the-audience-claim-before-consuming-an-mcp-resource-token.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-the-audience-claim-before-consuming-an-mcp-resource-token.warrant.json
# Markdown SHA-256:   906a967e40e03fc2ce07843326d98b937367f50baeff03a4c44b0641d7a94f32
# Code AST SHA-256:   3a661b0504171f931abdd717a05fc6b17b76af1aa093af14c3ddc4a2dc9c3f80
# Verified Classes:   AudienceBindingError, McpResourceServer
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AudienceBindingError(RuntimeError):
    """Raised when an MCP bearer token is not audience-bound to this resource server."""


@dataclass(frozen=True)
class McpResourceServer:
    canonical_id: str          # e.g. "https://deploy.mcp.internal"
    trusted_issuer: str        # e.g. "https://auth.internal"

    def _normalize(self, uri: str) -> str:
        return uri.rstrip("/").lower()

    def validate_token(self, claims: dict) -> None:
        # 1. Issuer must be the trusted AS. Signature assumed verified upstream.
        if claims.get("iss") != self.trusted_issuer:
            raise AudienceBindingError(
                f"issuer mismatch: {claims.get('iss')!r} != {self.trusted_issuer!r}"
            )

        # 2. Audience must name THIS resource server, exactly, as a member.
        aud = claims.get("aud")
        if aud is None:
            raise AudienceBindingError("token has no aud claim; refusing unbound token")
        aud_list = [aud] if isinstance(aud, str) else list(aud)
        if not aud_list:
            raise AudienceBindingError("empty aud claim")

        normalized_self = self._normalize(self.canonical_id)
        normalized_aud = {self._normalize(a) for a in aud_list}

        # Reject wildcard audiences outright: they re-open deputy confusion.
        if any("*" in a for a in normalized_aud):
            raise AudienceBindingError("wildcard aud is not admissible at a leaf MCP server")

        # Reject client-audienced tokens: aud naming the client is the classic deputy shape.
        if claims.get("azp") and self._normalize(claims["azp"]) in normalized_aud:
            raise AudienceBindingError("aud names the client (azp); confused-deputy token")

        if normalized_self not in normalized_aud:
            raise AudienceBindingError(
                f"audience mismatch: token aud={sorted(normalized_aud)} "
                f"does not include resource {normalized_self!r}"
            )

        # 3. Leaf servers reject multi-audience tokens unless explicitly a gateway.
        if len(normalized_aud) > 1:
            raise AudienceBindingError(
                f"multi-audience token at leaf server: {sorted(normalized_aud)}"
            )

    def dispatch_tool(self, claims: dict, tool_name: str) -> str:
        self.validate_token(claims)  # gate before any side effect
        token_fp = hashlib.sha256(
            f"{claims.get('jti')}:{self.canonical_id}".encode()
        ).hexdigest()[:12]
        return f"dispatched {tool_name!r} under token_fp={token_fp}"


def handle_mcp_request(server: McpResourceServer, claims: dict, tool_name: str) -> str:
    try:
        return server.dispatch_tool(claims, tool_name)
    except AudienceBindingError:
        # Fail closed: no tool resolution, no side effect, attributable 401.
        raise
