# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-oauth-token-audience-confusion-from-silently-widening-tool-scope-across-a-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-oauth-token-audience-confusion-from-silently-widening-tool-scope-across-a-session.warrant.json
# Markdown SHA-256:   562e022a018d9fcce8ac9c7c89a771daa39e4e3663365d83c4b63dd9ea5ece2f
# Code AST SHA-256:   398bfe81a8089220380c6792b9ad5602cc85157a8be5fd742920ac270b252c65
# Verified Classes:   AudienceMismatchError, Token, SessionPrincipal, ToolSpec
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class AudienceMismatchError(RuntimeError):
    """Raised when a tools/call is dispatched under a token whose aud
    does not cover the target tool's resource indicator."""


@dataclass(frozen=True)
class Token:
    subject: str
    aud: frozenset[str]          # RFC 8707 resource indicators
    scopes: frozenset[str]
    raw: str


@dataclass(frozen=True)
class SessionPrincipal:
    subject: str
    scopes: frozenset[str]
    # NOTE: aud intentionally retained; a principal without aud is the bug.


@dataclass(frozen=True)
class ToolSpec:
    name: str
    resource_indicator: str      # e.g. "mcp://obs/creds"
    required_scope: str


def dispatch_tool_call(
    session: SessionPrincipal,
    presented_token: Optional[Token],
    tool: ToolSpec,
) -> str:
    # Invariant: audience must be evaluated at dispatch, not at session open.
    # If the session principal carries aud, use it; otherwise require the raw
    # token. Never fall through to scope-only authorization.
    if presented_token is not None:
        aud = presented_token.aud
    else:
        # Session-only path is permitted ONLY if the session was opened with
        # an audience that already covers this tool.
        aud = getattr(session, "aud", frozenset())

    if tool.resource_indicator not in aud:
        raise AudienceMismatchError(
            f"tool={tool.name!r} requires aud={tool.resource_indicator!r}; "
            f"token aud={sorted(aud)!r}. Refusing cross-audience dispatch "
            f"under session subject={session.subject!r}."
        )

    if tool.required_scope not in session.scopes:
        raise AudienceMismatchError(
            f"tool={tool.name!r} requires scope={tool.required_scope!r}; "
            f"session scopes={sorted(session.scopes)!r}."
        )

    return f"executed {tool.name} for {session.subject}"


# Reproduction of the observed bypass, now correctly rejected:
metrics_tool = ToolSpec("query_metrics", "mcp://obs/metrics", "obs:read")
creds_tool   = ToolSpec("rotate_credentials", "mcp://obs/creds", "obs:admin")

session = SessionPrincipal(
    subject="agent-7",
    scopes=frozenset({"obs:read", "obs:admin"}),
)
# Session opened with a metrics-audience token; aud must be carried.
session_with_aud = SessionPrincipal(
    subject="agent-7",
    scopes=frozenset({"obs:read", "obs:admin"}),
)
# Simulate the fixed server: attach aud to the principal at session open.
object.__setattr__(session_with_aud, "aud", frozenset({"mcp://obs/metrics"}))

print(dispatch_tool_call(session_with_aud, None, metrics_tool))  # ok
try:
    dispatch_tool_call(session_with_aud, None, creds_tool)       # must fail
except AudienceMismatchError as e:
    print("blocked:", e)
