# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-multiplexed-http-native-mcp-stream-as-a-fresh-authorization-principal-rather-than-a-continuation-of-the.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-multiplexed-http-native-mcp-stream-as-a-fresh-authorization-principal-rather-than-a-continuation-of-the.warrant.json
# Markdown SHA-256:   79c5707d58f85ca4272854c1c346cb2454910995a9267fb59fd31b2a4b3be6bd
# Code AST SHA-256:   d63ef38a9aef0562e12c3ee4164e795a7e0f22e63d36822a2558802e734eaec8
# Verified Classes:   PrincipalMismatchError, ScopeNarrowingViolation
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class PrincipalMismatchError(RuntimeError):
    """Raised when a stream's envelope token resolves to a principal
    different from the principal pinned at connection establishment."""
    pass


class ScopeNarrowingViolation(RuntimeError):
    """Raised when an envelope token attempts to widen scope beyond the
    connection bearer, or when effective scope is miscomputed."""
    pass


def admit_stream(connection_principal_sub: str, envelope_token: dict) -> str:
    """Enforce C1: all streams on a connection must share one principal.

    Returns the pinned principal sub on success. Raises PrincipalMismatchError
    if the envelope token's sub differs from the connection's pinned sub.
    """
    envelope_sub = envelope_token.get("sub")
    if envelope_sub is None:
        raise PrincipalMismatchError(
            "envelope token carries no sub claim; cannot bind to connection"
        )
    if envelope_sub != connection_principal_sub:
        raise PrincipalMismatchError(
            f"stream sub={envelope_sub!r} does not match connection "
            f"pinned sub={connection_principal_sub!r}; "
            f"client must open a new connection for a different principal"
        )
    return connection_principal_sub


def authorize_tool_call(
    connection_scopes: frozenset,
    envelope_token: dict,
    required_scope: str,
) -> frozenset:
    """Enforce C2: effective scope = connection scopes INTERSECT envelope scopes.

    The envelope token may only narrow, never widen. Authorization is checked
    against the intersection, not against connection scopes alone.
    """
    envelope_scopes = frozenset(envelope_token.get("scopes", ()))
    if not envelope_scopes.issubset(connection_scopes):
        # An envelope token claiming scopes the connection bearer lacks is
        # either a forgery or a misconfigured delegation. Reject outright.
        raise ScopeNarrowingViolation(
            f"envelope scopes {sorted(envelope_scopes)} are not a subset of "
            f"connection scopes {sorted(connection_scopes)}; "
            f"envelope tokens may only narrow"
        )
    effective = connection_scopes & envelope_scopes
    if required_scope not in effective:
        raise ScopeNarrowingViolation(
            f"tool call requires {required_scope!r}; effective scope after "
            f"intersection is {sorted(effective)}; "
            f"connection-only authorization is unsound under multiplexing"
        )
    return effective


def handle_tools_call(
    connection_principal_sub: str,
    connection_scopes: frozenset,
    envelope_token: dict,
    required_scope: str,
) -> dict:
    """Full per-stream authorization path. Every tools/call goes through here."""
    # Admission check (C1). Cheap, re-run per stream; do not cache result.
    admit_stream(connection_principal_sub, envelope_token)

    # Per-call scope intersection (C2). Never authorize against connection
    # scopes alone; that is the delegation-attribution failure.
    effective = authorize_tool_call(connection_scopes, envelope_token, required_scope)

    return {
        "principal": envelope_token["sub"],
        "delegation_depth": envelope_token.get("delegation_depth", 0),
        "effective_scopes": sorted(effective),
        "authorized": True,
    }
