# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-tool-call-as-unauthorized-when-the-oauth-2-1-bearer-token-validates-but-its-aud-claim-does-not-bin.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-an-mcp-tool-call-as-unauthorized-when-the-oauth-2-1-bearer-token-validates-but-its-aud-claim-does-not-bin.warrant.json
# Markdown SHA-256:   b3085046717441c0e8b03a181602f944f4341e0da1e75103e230a4e7431ec782
# Code AST SHA-256:   c6b58e18c6fc28c690c6d5f170910295b977240c2861aeb34e53927af712eeaa
# Verified Classes:   TokenBindingError, Token, ToolDescriptor
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class TokenBindingError(RuntimeError):
    """Raised when a bearer token validates cryptographically but is not bound
    to the resource URI of the tool being invoked."""


@dataclass
class Token:
    subject: str
    audience: list[str]
    scopes: list[str]
    expires_at: float
    issuer: str


@dataclass
class ToolDescriptor:
    name: str
    resource_uri: str          # canonical URI, e.g. mcp://server/tools/execute
    required_scope: str


def _normalize_uri(uri: str) -> str:
    # No trailing slash, lowercase scheme+host, preserve path case.
    scheme, rest = uri.split("://", 1)
    host, _, path = rest.partition("/")
    return f"{scheme.lower()}://{host.lower()}/{path}".rstrip("/")


def authorize_tool_call(
    token: Token,
    tool: ToolDescriptor,
    now: Optional[float] = None,
) -> None:
    now = now if now is not None else time.time()

    # Cryptographic / temporal validity is assumed already checked upstream;
    # we re-check expiry defensively.
    if token.expires_at <= now:
        raise TokenBindingError(
            f"token expired at {token.expires_at}, now={now}"
        )

    # Binding check: the tool's resource URI must be an exact audience member.
    target = _normalize_uri(tool.resource_uri)
    audiences = {_normalize_uri(a) for a in token.audience}
    if target not in audiences:
        # This is the boundary failure: token is valid, scope may match,
        # but audience does not bind to this tool's resource.
        raise TokenBindingError(
            f"token aud={sorted(audiences)} does not bind to tool "
            f"resource={target!r} for tool={tool.name!r}"
        )

    # Scope containment, not mere presence.
    if tool.required_scope not in token.scopes:
        raise TokenBindingError(
            f"token scopes={token.scopes} missing required "
            f"{tool.required_scope!r} for tool={tool.name!r}"
        )


# --- Reproduction of the observed failure ---
if __name__ == "__main__":
    cached = Token(
        subject="agent-7",
        audience=["mcp://agent.example/server"],   # server URI, not tool URI
        scopes=["docs:read"],
        expires_at=time.time() + 300,
        issuer="https://auth.example",
    )
    execute_tool = ToolDescriptor(
        name="execute",
        resource_uri="mcp://agent.example/server/tools/execute",
        required_scope="exec:run",
    )
    try:
        authorize_tool_call(cached, execute_tool)
    except TokenBindingError as e:
        print(f"BLOCKED: {e}")   # expected: aud does not bind to tool resource
    else:
        raise TokenBindingError(
            "invariant violated: server-audience token authorized tool call"
        )
