# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-validates-origin-on-a-dns-rebinding-mcp-endpoint-but-binds-the-session-token-to-a-hostname-rather-than-a-resolved-peer.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-validates-origin-on-a-dns-rebinding-mcp-endpoint-but-binds-the-session-token-to-a-hostname-rather-than-a-resolved-peer.warrant.json
# Markdown SHA-256:   24976d258ee963a0b5a6abe38157771510bc73782f3fe9eefa582a2ac7b466d9
# Code AST SHA-256:   357120486ea05a6ae6fbb2e29904ae74186fdc145511682ac3052e0e87456dfa
# Verified Classes:   SessionBindingError, SessionRecord
# Defensive Guards:   7 fail-closed invariants (zero external deps)

import ipaddress
from dataclasses import dataclass
from typing import Optional


class SessionBindingError(RuntimeError):
    """Raised when an MCP session token is presented from an unbound peer or with an invalid Origin claim."""


@dataclass(frozen=True)
class SessionRecord:
    token: str
    peer_ip: str          # resolved remote_addr at issuance, NOT Host header
    token_class: str      # "browser" | "non-browser"
    origin_claim: Optional[str]  # only meaningful for browser class


ORIGIN_ALLOWLIST = frozenset({"https://app.example", "https://admin.example"})


def validate_request(
    record: SessionRecord,
    presented_token: str,
    remote_addr: str,
    origin_header: Optional[str],
    host_header: str,
) -> None:
    # Clause 1: transport-level peer binding. This is the load-bearing check.
    if presented_token != record.token:
        raise SessionBindingError("token mismatch")
    if ipaddress.ip_address(remote_addr) != ipaddress.ip_address(record.peer_ip):
        raise SessionBindingError(
            f"peer IP {remote_addr} does not match bound peer {record.peer_ip}"
        )

    # Clause 2: Origin is an *additive* gate, never a substitute for clause 1.
    if record.token_class == "browser":
        if origin_header is None:
            raise SessionBindingError("browser-class token requires Origin header")
        if origin_header not in ORIGIN_ALLOWLIST:
            raise SessionBindingError(f"origin {origin_header!r} not allowlisted")
    elif record.token_class == "non-browser":
        # Non-browser clients legitimately omit Origin; clause 1 is the only gate.
        if origin_header is not None and origin_header not in ORIGIN_ALLOWLIST:
            raise SessionBindingError(f"non-browser token presented with untrusted origin {origin_header!r}")

    # Clause 3: Host header must never select a session. It may only select config.
    # Assert this invariant explicitly so a future refactor cannot silently reintroduce Host-keying.
    if host_header and host_header.split(":")[0] not in {"mcp.internal.example", "127.0.0.1", "localhost"}:
        raise SessionBindingError(f"unexpected Host {host_header!r} on bound session")


def handle_tool_call(record, token, remote_addr, origin, host, tool_name):
    validate_request(record, token, remote_addr, origin, host)
    if tool_name == "shell.exec":
        # Warrant must be checked per-call, never inferred from session flags.
        raise SessionBindingError("shell.exec requires an explicit warrant; session flags are not authorization")
    return {"ok": True}
