# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-an-oauth-token-minted-for-one-mcp-resource-server-and-replay-it-against-another-tool-endpoint.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-an-oauth-token-minted-for-one-mcp-resource-server-and-replay-it-against-another-tool-endpoint.warrant.json
# Markdown SHA-256:   7f4f6354e8370d839d7771e3b007f448aac9b131cb7a45186ed62d6a4648b961
# Code AST SHA-256:   49ef9e14095f6efd62eb5a81ba414cbb9997f5e55451ddbe364ab97e24403fe6
# Verified Classes:   AudienceBindingError, AccessToken, ResourceServer
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import time
from dataclasses import dataclass
from typing import Optional


class AudienceBindingError(RuntimeError):
    """Raised when a token is presented to an RS it was not minted for."""


@dataclass(frozen=True)
class AccessToken:
    value: str
    issuer: str
    audience: tuple[str, ...]
    scopes: frozenset[str]
    expires_at: float


@dataclass(frozen=True)
class ResourceServer:
    resource_id: str          # canonical RFC 8707 identifier
    issuer: str
    enforces_audience: bool   # positive evidence from protected-resource metadata


def dispatch_tool_call(
    token: Optional[AccessToken],
    rs: ResourceServer,
    tool_required_scope: Optional[str],
    now: Optional[float] = None,
) -> str:
    now = now if now is not None else time.time()

    if token is None:
        raise AudienceBindingError("no token available for dispatch")

    if token.expires_at <= now:
        raise AudienceBindingError(f"token expired at {token.expires_at}")

    if token.issuer != rs.issuer:
        raise AudienceBindingError(
            f"issuer mismatch: token.iss={token.issuer} rs.issuer={rs.issuer}"
        )

    # The invariant: audience MUST name the receiving RS. Reuse across
    # resources is only permitted when the RS is known to enforce aud itself.
    if rs.resource_id not in token.audience:
        if not rs.enforces_audience:
            raise AudienceBindingError(
                f"token aud={token.audience} does not contain {rs.resource_id} "
                f"and {rs.resource_id} does not enforce audience binding; "
                f"refusing cross-resource reuse"
            )
        # RS enforces aud; it will reject. Do not pre-empt, but do not
        # treat success as evidence of capability.
        return f"deferred:aud_enforced:{rs.resource_id}"

    if tool_required_scope is None:
        raise AudienceBindingError(
            f"tool on {rs.resource_id} declares no required_scope; "
            f"cannot verify least-privilege"
        )

    if tool_required_scope not in token.scopes:
        raise AudienceBindingError(
            f"scope {tool_required_scope!r} not in token scopes {sorted(token.scopes)}"
        )

    return f"ok:{rs.resource_id}:{tool_required_scope}"


def run_dispatch_example() -> None:
    tok = AccessToken(
        value="eyJ...",
        issuer="https://as.internal",
        audience=("https://files-rs.internal",),
        scopes=frozenset({"files:read"}),
        expires_at=time.time() + 300,
    )
    db_rs = ResourceServer(
        resource_id="https://db-rs.internal",
        issuer="https://as.internal",
        enforces_audience=False,
    )
    # This is the exact failure the article describes: a files token
    # replayed against db-rs whose protected-resource metadata does not
    # advertise audience enforcement.
    dispatch_tool_call(tok, db_rs, tool_required_scope="db:query")


if __name__ == "__main__":
    run_dispatch_example()
