# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-scope-bleed-when-an-http-native-mcp-server-multiplexes-concurrent-requests-over-a-shared-session.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-scope-bleed-when-an-http-native-mcp-server-multiplexes-concurrent-requests-over-a-shared-session.warrant.json
# Markdown SHA-256:   6eada89fa0d53b9a1d9faf8ba48bbdf39566e2a2ec20ece11e153e7558ba4706
# Code AST SHA-256:   f6a339a6c4afcbd36c3ac06a9338325c8124b923dd56fc202846e9a4b1566ca5
# Verified Classes:   ScopeBleedError, CallScope, SessionContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import threading
from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeBleedError(RuntimeError):
    """Raised when a resource access is authorized against a scope that was
    produced by a different request than the one currently executing."""


@dataclass(frozen=True)
class CallScope:
    request_id: str
    resources: FrozenSet[str]


class SessionContext:
    """Mutable session state. Authorization must NEVER read from here."""

    def __init__(self) -> None:
        self._lock = threading.Lock()
        self._cached_scope: CallScope | None = None

    def store_scope(self, scope: CallScope) -> None:
        with self._lock:
            self._cached_scope = scope

    def peek_scope(self) -> CallScope | None:
        with self._lock:
            return self._cached_scope


def authorize(
    scope: CallScope,
    current_request_id: str,
    resource: str,
) -> None:
    """Assert that `resource` is covered by `scope`, and that `scope` was
    derived from the currently executing request. Fails closed on mismatch."""
    if scope.request_id != current_request_id:
        raise ScopeBleedError(
            f"scope for request {scope.request_id!r} used while executing "
            f"request {current_request_id!r}"
        )
    if resource not in scope.resources:
        raise ScopeBleedError(
            f"request {current_request_id!r} lacks scope for resource {resource!r}; "
            f"has {sorted(scope.resources)}"
        )


def handle_tool_call(
    session: SessionContext,
    request_id: str,
    declared_scope: CallScope,
    resources: list[str],
) -> None:
    # Bind scope to this request; do not read session auth state.
    if declared_scope.request_id != request_id:
        raise ScopeBleedError(
            f"declared scope {declared_scope.request_id!r} does not match "
            f"request {request_id!r}"
        )
    # Detect if another principal has mutated the session mid-flight.
    cached = session.peek_scope()
    if cached is not None and cached.request_id != request_id:
        # Informational only: authorization below uses declared_scope.
        pass
    for resource in resources:
        authorize(declared_scope, request_id, resource)
    session.store_scope(declared_scope)
