# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-mcp-mutual-tls-attestation-has-silently-degraded-to-server-name-only-trust.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-mcp-mutual-tls-attestation-has-silently-degraded-to-server-name-only-trust.warrant.json
# Markdown SHA-256:   8eabb43db10f0a11c3b2ed28d9e5ed0fd777158c4490de2eee0a6d83f654799a
# Code AST SHA-256:   8c09136979e7875374e3088f64d080cddaf24361ea160f795721c54b8d3918de
# Verified Classes:   AttestationDowngradeError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
import hmac


class AttestationDowngradeError(RuntimeError):
    """Raised when mTLS completed but the attested instance cannot be bound to the TLS peer."""
    pass


def verify_mcp_session(
    tls_peer_spki: bytes,
    pinned_spki: bytes,
    initialize_response: dict,
    attestation_token: bytes | None,
    attestation_issuer_key: bytes | None,
) -> str:
    """
    Returns 'attested' only if the TLS peer is bound to the MCP server instance
    that produced initialize_response. Returns 'channel-only' if mTLS passed but
    the instance binding cannot be verified. Raises on hard failures.
    """
    if not hmac.compare_digest(tls_peer_spki, pinned_spki):
        raise AttestationDowngradeError(
            f"TLS peer SPKI {tls_peer_spki.hex()[:16]}... does not match pinned "
            f"{pinned_spki.hex()[:16]}..."
        )

    # The pin matched. That proves the channel. It does NOT prove the instance.
    server_info = initialize_response.get("serverInfo", {})
    instance_id = server_info.get("name"), server_info.get("version")
    if not all(instance_id):
        # No instance identity asserted at all: pure channel trust.
        return "channel-only"

    if attestation_token is None or attestation_issuer_key is None:
        # Server asserted an identity but supplied no binding to it.
        # We cannot distinguish "same instance" from "ingress proxying elsewhere".
        return "channel-only"

    expected = hmac.new(
        attestation_issuer_key,
        f"{server_info['name']}:{server_info['version']}".encode(),
        hashlib.sha256,
    ).digest()
    if not hmac.compare_digest(attestation_token, expected):
        raise AttestationDowngradeError(
            "Attestation token does not bind the initialize response to the "
            "attested instance; possible TLS-terminating intermediary substitution."
        )
    return "attested"


def authorize_tool_call(session_state: str, tool_name: str, side_effecting: bool) -> None:
    if side_effecting and session_state != "attested":
        raise AttestationDowngradeError(
            f"Refusing side-effecting tool '{tool_name}' on session state "
            f"'{session_state}': mTLS channel trust is not instance attestation."
        )
