# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-confused-deputy-tool-invocation-when-mcp-streamable-http-transport-collapses-the-origin-authorization-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-confused-deputy-tool-invocation-when-mcp-streamable-http-transport-collapses-the-origin-authorization-boundary.warrant.json
# Markdown SHA-256:   882c327d801702033705d8d2b9405282c1e83d1314903c61aaf8ade23e9913b4
# Code AST SHA-256:   cbcc447e98eeba86afc35072222cae6340f854eb21ddd852828f34f1a950c235
# Verified Classes:   ConfusedDeputyError
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import re
from typing import Any

CREDENTIAL_SHAPE = re.compile(
    r'"(AccessKeyId|SecretAccessKey|SessionToken|Token)"\s*:'
)
LINK_LOCAL = ("169.254.", "127.", "10.", "192.168.", "172.16.", "172.17.",
              "172.18.", "172.19.", "172.2", "172.30.", "172.31.")


class ConfusedDeputyError(RuntimeError):
    """Raised when a tool invocation would act outside the caller's authority."""


def guard_tool_call(
    caller_aud: str,
    inbound_host: str,
    tool_target: str,
    forwards_caller_auth: bool,
    response_body: Any,
) -> None:
    if caller_aud != inbound_host:
        raise ConfusedDeputyError(
            f"audience/host mismatch: aud={caller_aud!r} host={inbound_host!r}; "
            "refusing to invoke deputy tool (possible ingress rewrite)"
        )
    if forwards_caller_auth and any(
        tool_target.startswith(p) for p in LINK_LOCAL
    ):
        raise ConfusedDeputyError(
            f"tool target {tool_target!r} is link-local/private and the tool "
            "forwards caller Authorization; refusing (SSRF+credential leak)"
        )
    if isinstance(response_body, str) and CREDENTIAL_SHAPE.search(response_body):
        raise ConfusedDeputyError(
            "tool response contains credential-shaped JSON; halting reasoning "
            "loop and quarantining session"
        )
