# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-mcp-session-hijack-after-transport-re-binding-from-silently-widening-per-tool-authorization-scopes.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-mcp-session-hijack-after-transport-re-binding-from-silently-widening-per-tool-authorization-scopes.warrant.json
# Markdown SHA-256:   0d33f75dfaa78ace6f92e3285b6fa4d586366ee6676d57deea79e5ae0bfb60a1
# Code AST SHA-256:   e837b39b660bb2866dad1da926cfa7b317269fa9513e5cd4e618224b2d1edb4f
# Verified Classes:   ScopeReconciliationError, Session
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeReconciliationError(RuntimeError):
    """Raised when a resumed MCP session's cached scopes diverge from the
    re-authenticated principal's scopes and the divergence is unhandled."""


@dataclass
class Session:
    session_id: str
    origin_principal: str
    scopes: FrozenSet[str]
    advertised_tools: FrozenSet[str] = field(default_factory=frozenset)


def resume_session(
    session: Session,
    new_principal: str,
    new_token_scopes: FrozenSet[str],
    tool_scope_map: dict,  # tool_name -> required_scope
) -> Session:
    """Re-bind an existing MCP session to a re-authenticated principal.

    Invariant: scope(session) must equal scopes(token) at every rebind.
    A resumed session may never carry scopes broader than the live token.
    """
    # The dangerous case: rebind to a *different* principal.
    if new_principal != session.origin_principal:
        raise ScopeReconciliationError(
            f"session {session.session_id} originated under principal "
            f"{session.origin_principal!r}, rebind attempted by "
            f"{new_principal!r}; refusing cross-principal resume"
        )

    # Same principal, but token scope may have narrowed (revocation).
    effective = session.scopes & new_token_scopes
    if effective != session.scopes:
        # Narrowing is a revocation event; must not be silently ignored.
        still_authorized = frozenset(
            t for t in session.advertised_tools
            if tool_scope_map.get(t) in effective
        )
        if still_authorized != session.advertised_tools:
            raise ScopeReconciliationError(
                f"session {session.session_id} scope narrowed from "
                f"{sorted(session.scopes)} to {sorted(effective)}; "
                f"tools {sorted(session.advertised_tools - still_authorized)} "
                f"must be withdrawn via notifications/tools/list_changed "
                f"before resume is permitted"
            )
        session.scopes = effective

    return session


def authorize_tool_call(
    session: Session,
    principal: str,
    tool: str,
    tool_scope_map: dict,
) -> None:
    """Per-tool authorization must read from the reconciled session scope,
    and must additionally verify the caller matches the session origin."""
    if principal != session.origin_principal:
        raise ScopeReconciliationError(
            f"principal {principal!r} invoked {tool!r} on session "
            f"{session.session_id} owned by {session.origin_principal!r}"
        )
    required = tool_scope_map.get(tool)
    if required is None:
        raise ScopeReconciliationError(f"unknown tool {tool!r}")
    if required not in session.scopes:
        raise ScopeReconciliationError(
            f"principal {principal!r} lacks scope {required!r} for {tool!r}"
        )
