# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-oauth-2-1-resource-indicator-scoping-has-silently-collapsed-to-token-wide-consent-in-mcp-tool-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-oauth-2-1-resource-indicator-scoping-has-silently-collapsed-to-token-wide-consent-in-mcp-tool-invocation.warrant.json
# Markdown SHA-256:   fc8571a0de7410f8e31cce29441f4bdaa52aeb582135a9a848fa12d48b9c942e
# Code AST SHA-256:   fb0e1a7e3ef9ae8060f156f2e08669bf2cb47fa79868d6393360cbe10cdc180d
# Verified Classes:   ResourceScopeCollapseError, ConsentRecord, InvocationContext
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ResourceScopeCollapseError(RuntimeError):
    """Raised when a token's grant is not bound to the resource indicator
    that produced the consent, indicating silent collapse to token-wide consent."""


@dataclass(frozen=True)
class ConsentRecord:
    resource_indicator: str
    granted_scopes: frozenset[str]
    tool_owner: str


@dataclass(frozen=True)
class InvocationContext:
    token_audience: str
    token_scopes: frozenset[str]
    resolved_tool_owner: str
    exchange_chain: tuple[str, ...]  # resource values seen at each hop; "" if dropped


def _canonical(resource: str) -> str:
    # Single canonicalization: lowercase scheme+host, strip trailing slash.
    # No prefix or substring tolerance is permitted past this point.
    return resource.rstrip("/").lower()


def assert_grant_bound_to_resource(
    consent: ConsentRecord,
    invocation: InvocationContext,
    configured_resource: str,
) -> None:
    # 1. Exact audience equality against the server's own resource string.
    if _canonical(invocation.token_audience) != _canonical(configured_resource):
        raise ResourceScopeCollapseError(
            f"audience mismatch: token aud={invocation.token_audience!r} "
            f"!= configured resource={configured_resource!r}"
        )

    # 2. Consent record must name the same resource indicator that produced the token.
    if _canonical(consent.resource_indicator) != _canonical(invocation.token_audience):
        raise ResourceScopeCollapseError(
            f"consent resource {consent.resource_indicator!r} does not bind "
            f"token audience {invocation.token_audience!r}"
        )

    # 3. Every exchange hop must carry a resource value; a dropped resource is
    #    a token-wide grant by construction.
    for hop_index, hop_resource in enumerate(invocation.exchange_chain):
        if not hop_resource:
            raise ResourceScopeCollapseError(
                f"token exchange hop {hop_index} dropped the resource indicator; "
                f"grant is token-wide, not resource-scoped"
            )
        if _canonical(hop_resource) != _canonical(configured_resource):
            raise ResourceScopeCollapseError(
                f"token exchange hop {hop_index} re-scoped to {hop_resource!r}, "
                f"diverging from {configured_resource!r}"
            )

    # 4. Invoked tool must belong to the consenting resource's tool surface.
    if invocation.resolved_tool_owner != consent.tool_owner:
        raise ResourceScopeCollapseError(
            f"tool owner {invocation.resolved_tool_owner!r} diverges from "
            f"consent owner {consent.tool_owner!r}; consent-to-invocation "
            f"divergence rate must be zero"
        )

    # 5. Scopes must be a subset of the consent grant, not merely present on token.
    if not invocation.token_scopes.issubset(consent.granted_scopes):
        raise ResourceScopeCollapseError(
            f"token scopes {sorted(invocation.token_scopes)} exceed consent "
            f"grant {sorted(consent.granted_scopes)}"
        )
