# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-sse-to-streamable-http-upgrade-from-silently-rebinding-a-per-tool-oauth-resource-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-sse-to-streamable-http-upgrade-from-silently-rebinding-a-per-tool-oauth-resource-mid-session.warrant.json
# Markdown SHA-256:   7b3686eea044ea709c0deb8b6c40bb8bf128490a3bb62ec886f8ea7227a96921
# Code AST SHA-256:   c7c606ae517317e9d0fa852acd929e1b87a889d29f22de9b4fcd0b3a3b77867d
# Verified Classes:   ResourceBindingMismatch, SessionRecord
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class ResourceBindingMismatch(RuntimeError):
    """Raised when a transport upgrade would silently rebind the session's OAuth resource."""
    pass


@dataclass
class SessionRecord:
    session_id: str
    resource: str          # pinned at initialize, immutable across transport legs
    transport: str         # "sse" | "streamable-http"
    grant_id: str
    lineage: list = field(default_factory=list)


def _canonical(url: str) -> str:
    # strip default ports, lowercase scheme/host, drop trailing slash
    scheme, rest = url.split("://", 1)
    host, _, path = rest.partition("/")
    host = host.split(":")[0] if host.endswith(":443") or host.endswith(":80") else host
    return f"{scheme.lower()}://{host.lower()}/{path.rstrip('/')}"


def upgrade_transport(
    session: SessionRecord,
    new_endpoint: str,
    new_session_id: str,
    as_registry: dict,   # exact-match resource -> policy
) -> SessionRecord:
    # INVARIANT 1: resource is copied forward, never recomputed from new_endpoint
    inherited_resource = session.resource

    # INVARIANT 2: the new leg's canonical URL must not be used to derive resource
    derived_from_url = _canonical(new_endpoint)
    if derived_from_url != _canonical(inherited_resource):
        # upgrade endpoint differs from bound resource; that is legal only if
        # the AS has an exact entry for the *inherited* resource and the
        # upgrade is treated as transport-only. We do NOT request a new
        # resource for the new endpoint.
        pass

    # INVARIANT 3: AS must have an exact-match entry for the inherited resource.
    # Prefix matching here is what silently widens scope.
    if _canonical(inherited_resource) not in as_registry:
        raise ResourceBindingMismatch(
            f"AS has no exact-match grant for resource {inherited_resource!r}; "
            f"refusing upgrade that would rebind to {derived_from_url!r}"
        )

    # INVARIANT 4: session id rotates, resource does not.
    upgraded = SessionRecord(
        session_id=new_session_id,
        resource=inherited_resource,
        transport="streamable-http",
        grant_id=session.grant_id,
        lineage=session.lineage + [session.session_id],
    )
    return upgraded


def validate_tool_call(session: SessionRecord, requested_resource: str) -> None:
    # INVARIANT 5: tool dispatch validates against stored resource, not request URL.
    if _canonical(requested_resource) != _canonical(session.resource):
        raise ResourceBindingMismatch(
            f"tool call requested resource {requested_resource!r} "
            f"but session {session.session_id} is bound to {session.resource!r}"
        )
