# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-forwarded-bearer-token-across-an-mcp-http-transport-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-forwarded-bearer-token-across-an-mcp-http-transport-boundary.warrant.json
# Markdown SHA-256:   48bd8de00844c894717f404e7d4a45523853635d9d1f4e7eff68acf21813dd9c
# Code AST SHA-256:   0f52edb012b3badcaf2ce1ff58c76a3aa2e15ecfd9adb395666b709fe54992e4
# Verified Classes:   ResourceBindingError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hmac
from urllib.parse import urlparse


class ResourceBindingError(RuntimeError):
    """Raised when a bearer token is not bound to this MCP resource,
    or when the request origin is not allowlisted. Fail-closed."""


CANONICAL_RESOURCE = "mcp://tools.internal"
ALLOWED_ORIGINS = frozenset({
    "https://orchestrator.example",
    "https://app.example",
})


def _aud_matches(aud, canonical: str) -> bool:
    # aud may be a string or list; require EXACT membership, never prefix.
    if isinstance(aud, str):
        return hmac.compare_digest(aud, canonical)
    if isinstance(aud, (list, tuple)):
        return any(hmac.compare_digest(a, canonical) for a in aud)
    return False


def enforce_resource_binding(claims: dict, origin: str | None, host: str | None) -> None:
    """Precondition gate for every HTTP-native MCP request.
    Must run BEFORE tool dispatch. Raises on any violation."""
    aud = claims.get("aud")
    if not _aud_matches(aud, CANONICAL_RESOURCE):
        # Confused-deputy / token-passthrough signature.
        raise ResourceBindingError(
            f"audience mismatch: token aud={aud!r} does not name {CANONICAL_RESOURCE!r}; "
            f"refusing forwarded/passthrough bearer token (jti={claims.get('jti')!r})"
        )

    if origin is None:
        # Non-browser client: Origin legitimately absent, but Host must be bound.
        if not host or urlparse(f"//{host}").hostname not in {
            "tools.internal", "localhost",
        }:
            raise ResourceBindingError(
                f"unbound Host header {host!r} with absent Origin; possible DNS rebinding"
            )
        return

    if origin == "null" or origin not in ALLOWED_ORIGINS:
        raise ResourceBindingError(
            f"origin {origin!r} not in allowlist; refusing cross-origin MCP call"
        )


def handle_mcp_request(claims: dict, origin: str | None, host: str | None, tool: str) -> str:
    enforce_resource_binding(claims, origin, host)
    return f"dispatched {tool} under aud={CANONICAL_RESOURCE}"
