# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-delegation-collapse-when-an-mcp-server-reuses-a-single-upstream-token-across-per-tool-least-privilege-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-delegation-collapse-when-an-mcp-server-reuses-a-single-upstream-token-across-per-tool-least-privilege-boundaries.warrant.json
# Markdown SHA-256:   2bba4e0f01e7630e49cce326f2c2991acfa483c2a3e84808c074dea6c4992819
# Code AST SHA-256:   f0ffa34867c76cb36761ac7058f61c5ed5789225fe472adc9cc548e28030db60
# Verified Classes:   ScopeDelegationCollapse, DelegatedToken, ScopeDelegatingMCPGateway
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ScopeDelegationCollapse(RuntimeError):
    """Raised when a cached delegated token over-privileges a per-tool call."""
    pass


@dataclass(frozen=True)
class DelegatedToken:
    value: str
    scope: FrozenSet[str]
    expires_at: float


class ScopeDelegatingMCPGateway:
    def __init__(self, exchange, cache=None):
        self._exchange = exchange
        self._cache = cache if cache is not None else {}

    def _mint(self, session_id: str, asserted: FrozenSet[str]) -> DelegatedToken:
        key = (session_id, asserted)
        if key in self._cache:
            return self._cache[key]
        token = self._exchange(session_id=session_id, scope=asserted)
        if not token.scope <= asserted:
            # Upstream returned authority the caller never asserted.
            raise ScopeDelegationCollapse(
                f"exchange returned scope {sorted(token.scope)} "
                f"exceeding asserted {sorted(asserted)}"
            )
        self._cache[key] = token
        return token

    def authorize_tool_call(
        self,
        session_id: str,
        tool_required_scope: FrozenSet[str],
        asserted_scopes: FrozenSet[str],
    ) -> DelegatedToken:
        if not tool_required_scope <= asserted_scopes:
            raise ScopeDelegationCollapse(
                f"tool requires {sorted(tool_required_scope)} not in "
                f"per-call assertion {sorted(asserted_scopes)}"
            )

        # The collapse: a session-level cached token that is a strict
        # superset of this call's assertion must never be forwarded.
        session_token = self._cache.get((session_id, asserted_scopes))
        if session_token is not None and session_token.scope > asserted_scopes:
            raise ScopeDelegationCollapse(
                f"cached token scope {sorted(session_token.scope)} is a strict "
                f"superset of asserted {sorted(asserted_scopes)}; refusing to "
                f"forward over-privileged bearer"
            )

        return self._mint(session_id, asserted_scopes)
