# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-propagation-across-mcp-server-boundaries-via-http-native-transport-headers.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-propagation-across-mcp-server-boundaries-via-http-native-transport-headers.warrant.json
# Markdown SHA-256:   0daa143343841511afffa3887a0b720b85ea3dfe13dc198cbcfbbdeea22c74d5
# Code AST SHA-256:   f7cd61177cdd7417561f1822d1df4389ed3deba00d9243ac76c149bc434e9c4e
# Verified Classes:   TaintBoundaryViolation, ProvenanceMismatch, ToolCall
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field
from typing import Iterable


class TaintBoundaryViolation(RuntimeError):
    """Raised when a privileged MCP tool call arrives without a clean provenance chain."""


class ProvenanceMismatch(TaintBoundaryViolation):
    """Raised when declared provenance does not match observed argument overlap."""


UNTRUSTED_SOURCES = frozenset({"web.fetch", "http.get", "browser.read", "email.read"})
PRIVILEGED_TOOLS = frozenset({"repo.write", "shell.exec", "secrets.read", "git.commit"})


@dataclass
class ToolCall:
    server: str
    tool: str
    arguments: dict
    meta: dict = field(default_factory=dict)
    session_id: str = ""


def _ngrams(text: str, n: int = 8) -> set[str]:
    tokens = re.findall(r"\w+", text.lower())
    return {" ".join(tokens[i:i + n]) for i in range(len(tokens) - n + 1)}


def _overlaps(a: str, b: str, threshold: float = 0.15) -> bool:
    ga, gb = _ngrams(a), _ngrams(b)
    if not ga or not gb:
        return False
    return len(ga & gb) / min(len(ga), len(gb)) >= threshold


def enforce_provenance(
    call: ToolCall,
    recent_untrusted_outputs: Iterable[str],
) -> None:
    """
    Fail closed on privileged tools lacking a clean provenance chain.
    Also flag the laundering footprint: empty _meta but high n-gram overlap
    with a recent untrusted tool result.
    """
    if call.tool not in PRIVILEGED_TOOLS:
        return

    chain = call.meta.get("provenance_chain")
    if chain is None:
        # Missing provenance on a privileged tool is the default-laundering path.
        flat_args = " ".join(str(v) for v in call.arguments.values())
        for blob in recent_untrusted_outputs:
            if _overlaps(flat_args, blob):
                raise ProvenanceMismatch(
                    f"privileged tool {call.tool!r} on {call.server!r} has no "
                    f"provenance_chain but its arguments overlap a recent "
                    f"untrusted tool result (session {call.session_id!r})"
                )
        raise TaintBoundaryViolation(
            f"privileged tool {call.tool!r} on {call.server!r} invoked without "
            f"provenance_chain in _meta; refusing to execute (fail-closed)"
        )

    if not isinstance(chain, list) or not chain:
        raise TaintBoundaryViolation(
            f"provenance_chain for {call.tool!r} must be a non-empty list; "
            f"got {type(chain).__name__}"
        )

    tainted = [src for src in chain if src in UNTRUSTED_SOURCES]
    if tainted:
        digest = hashlib.sha256(
            repr(sorted(call.arguments.items())).encode()
        ).hexdigest()[:12]
        raise TaintBoundaryViolation(
            f"privileged tool {call.tool!r} on {call.server!r} carries taint "
            f"from {tainted}; args digest {digest}; refusing to execute"
        )
