# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-a-streamable-http-mcp-session-to-its-dns-origin-before-honoring-origin-echoed-bearer-tokens-and-what-breaks-when-it-does-n.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-a-streamable-http-mcp-session-to-its-dns-origin-before-honoring-origin-echoed-bearer-tokens-and-what-breaks-when-it-does-n.warrant.json
# Markdown SHA-256:   2e5cddf9923f33d4d8032b2f029e5c0e8a43253759f79dfad44be9e5e86b2a75
# Code AST SHA-256:   5ff256a5ec2fb96e8aee8f861f7e2d2eebda68f94dfe4be8918edb7cf8a79048
# Verified Classes:   OriginBindingViolation, SessionKey
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class OriginBindingViolation(RuntimeError):
    """Raised when a streamable-HTTP MCP request fails the (token, session, origin) intersection."""


@dataclass(frozen=True)
class SessionKey:
    origin: str
    subject: str
    audience: str


def scoped_session_key(server_origin: str, token_sub: str, token_aud: str) -> SessionKey:
    if not server_origin or not token_sub or not token_aud:
        raise OriginBindingViolation("cannot form session key: missing origin/subject/audience")
    return SessionKey(origin=server_origin, subject=token_sub, audience=token_aud)


def admit_streamable_request(
    *,
    server_canonical_origin: str,
    request_origin_header: str | None,
    token_aud_claim: list[str] | str,
    token_sub: str,
    presented_session_id: str | None,
    session_store: dict[str, SessionKey],
) -> SessionKey:
    aud_set = {token_aud_claim} if isinstance(token_aud_claim, str) else set(token_aud_claim)

    # 1. Audience must name this exact origin; coarse gateway audiences are rejected.
    if server_canonical_origin not in aud_set:
        raise OriginBindingViolation(
            f"token audience {sorted(aud_set)} does not include origin {server_canonical_origin}"
        )

    # 2. Client-asserted Origin, when present, must match the server's canonical origin.
    if request_origin_header is not None and request_origin_header != server_canonical_origin:
        raise OriginBindingViolation(
            f"Origin header {request_origin_header!r} != canonical {server_canonical_origin!r}"
        )

    # 3. Resumption / teardown must present a session bound to this exact tuple.
    if presented_session_id is None:
        return scoped_session_key(server_canonical_origin, token_sub, server_canonical_origin)

    recorded = session_store.get(presented_session_id)
    if recorded is None:
        # Fail closed: never fall back to an unscoped lookup.
        raise OriginBindingViolation(f"unknown or unscoped session id {presented_session_id!r}")

    expected = SessionKey(
        origin=server_canonical_origin, subject=token_sub, audience=server_canonical_origin
    )
    if recorded != expected:
        raise OriginBindingViolation(
            f"session {presented_session_id!r} bound to {recorded} but request is {expected}"
        )
    return recorded


def mint_session_id(key: SessionKey) -> str:
    material = f"{key.origin}|{key.subject}|{key.audience}".encode()
    return "s-" + hashlib.sha256(material).hexdigest()[:16]


# Replay trace: token minted for tenant-a presented at tenant-b.
store: dict[str, SessionKey] = {}
key_a = scoped_session_key("https://mcp.tenant-a.internal", "sub-a", "https://mcp.tenant-a.internal")
store[mint_session_id(key_a)] = key_a

try:
    admit_streamable_request(
        server_canonical_origin="https://mcp.tenant-b.internal",
        request_origin_header="https://mcp.tenant-b.internal",
        token_aud_claim=["https://mcp.tenant-a.internal"],  # correctly scoped, still rejected at B
        token_sub="sub-a",
        presented_session_id=mint_session_id(key_a),
        session_store=store,
    )
except OriginBindingViolation as exc:
    raise OriginBindingViolation(f"replay blocked at origin intersection: {exc}") from exc
