# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-origin-header-validation-as-a-confused-deputy-boundary-rather-than-a-cors-convenience.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-origin-header-validation-as-a-confused-deputy-boundary-rather-than-a-cors-convenience.warrant.json
# Markdown SHA-256:   383a2daf747e3453d0673d660a3a7afb3d6409fa2a120e7b63648c35eaee972a
# Code AST SHA-256:   f374e123822bd661ebada2bea0b4f1a841664d0128cba71907125bdf5634878e
# Verified Classes:   ConfusedDeputyBoundaryError
# Defensive Guards:   7 fail-closed invariants (zero external deps)

class ConfusedDeputyBoundaryError(RuntimeError):
    """Raised when an MCP HTTP request cannot satisfy the conjunctive
    (origin, session-binding, token-binding) gate and must be rejected
    before dispatch. This is a security boundary, not a validation nit."""


ALLOWED_ORIGINS = frozenset({
    "https://console.example",
    "https://agent-host.example",
})


def authorize_mcp_request(
    origin: str | None,
    session_id: str | None,
    token_subject: str | None,
    token_bound_origin: str | None,
    session_store: dict[str, tuple[str, str]],  # session_id -> (subject, origin)
) -> None:
    """Fail-closed gate. Any single failure raises; no partial pass."""
    # 1. Origin must be present, exact, and never 'null' or reflected.
    if origin is None or origin == "null":
        raise ConfusedDeputyBoundaryError(
            f"missing/null Origin on credentialed MCP endpoint: {origin!r}"
        )
    if origin not in ALLOWED_ORIGINS:
        raise ConfusedDeputyBoundaryError(
            f"Origin {origin!r} not in exact allowlist; refusing dispatch"
        )

    # 2. Token must be bound to this origin, not merely to a subject.
    if token_subject is None or token_bound_origin is None:
        raise ConfusedDeputyBoundaryError(
            "token lacks subject or origin binding; cannot prove non-coercion"
        )
    if token_bound_origin != origin:
        raise ConfusedDeputyBoundaryError(
            f"token bound to {token_bound_origin!r} presented from {origin!r}"
        )

    # 3. Session must be bound to the same (subject, origin) pair.
    if session_id is None:
        raise ConfusedDeputyBoundaryError("missing Mcp-Session-Id on tools/call")
    record = session_store.get(session_id)
    if record is None:
        raise ConfusedDeputyBoundaryError(f"unknown session {session_id!r}")
    bound_subject, bound_origin = record
    if (bound_subject, bound_origin) != (token_subject, origin):
        raise ConfusedDeputyBoundaryError(
            f"session {session_id!r} bound to {(bound_subject, bound_origin)!r} "
            f"but presented as {(token_subject, origin)!r}"
        )


def dispatch_tools_call(request: dict, session_store: dict) -> dict:
    authorize_mcp_request(
        origin=request.get("origin"),
        session_id=request.get("session_id"),
        token_subject=request.get("subject"),
        token_bound_origin=request.get("bound_origin"),
        session_store=session_store,
    )
    return {"jsonrpc": "2.0", "id": request.get("id"), "result": {"ok": True}}
