# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-taint-tagging-mcp-tool-responses-still-leak-secrets-when-a-single-trusted-server-re-serializes-untrusted-content.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-taint-tagging-mcp-tool-responses-still-leak-secrets-when-a-single-trusted-server-re-serializes-untrusted-content.warrant.json
# Markdown SHA-256:   c84e6914bafdb554580c6d8496f80e431ec343d1266165ae9a85a8b5dd79f204
# Code AST SHA-256:   7e677ccc8d92a4e7521c1fec4fccf47dc81f4682e8254faeffb8202707339323
# Verified Classes:   TaintLaunderingError, TaintedValue, ServerProfile, TaintProxy
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a trusted server's output drops taint inherited from its arguments."""


@dataclass
class TaintedValue:
    value: Any
    taint: bool
    lineage: list[str] = field(default_factory=list)


@dataclass
class ServerProfile:
    name: str
    trusted: bool
    # "sink" | "transducer" | "sanitizer" | "opaque"
    kind: str


class TaintProxy:
    def __init__(self, profiles: dict[str, ServerProfile]):
        self.profiles = profiles
        self.declassification_log: list[dict] = []

    def call(self, server: str, tool: str, args: list[TaintedValue]) -> TaintedValue:
        prof = self.profiles[server]
        arg_taint = any(a.taint for a in args)
        arg_lineage = [f"{server}.{tool}"] + [l for a in args for l in a.lineage]

        # Untrusted server: output is always tainted.
        if not prof.trusted:
            return TaintedValue(value=f"<{server}.{tool} output>", taint=True, lineage=arg_lineage)

        # Trusted sink: output not used for propagation; guard on args.
        if prof.kind == "sink":
            if arg_taint:
                raise TaintLaunderingError(
                    f"sink {server}.{tool} rejected: tainted argument from {arg_lineage}"
                )
            return TaintedValue(value=None, taint=False, lineage=arg_lineage)

        # Trusted transducer / opaque: MUST preserve argument taint.
        if prof.kind in ("transducer", "opaque"):
            if arg_taint:
                # The server's own label is ignored; join is over arguments.
                return TaintedValue(
                    value=f"<{server}.{tool} output>",
                    taint=True,
                    lineage=arg_lineage,
                )
            return TaintedValue(value=f"<{server}.{tool} output>", taint=False, lineage=arg_lineage)

        # Sanitizer: only clean if a validator confirmed the tainted span is absent.
        if prof.kind == "sanitizer":
            validator_ok = self._validate_sanitizer(server, tool, args)
            if arg_taint and not validator_ok:
                raise TaintLaunderingError(
                    f"sanitizer {server}.{tool} claimed clean output but failed validation; "
                    f"lineage={arg_lineage}"
                )
            if arg_taint and validator_ok:
                self.declassification_log.append(
                    {"server": server, "tool": tool, "lineage": arg_lineage}
                )
            return TaintedValue(value=f"<{server}.{tool} output>", taint=not validator_ok, lineage=arg_lineage)

        raise TaintLaunderingError(f"unknown server kind {prof.kind!r} for {server}")

    def _validate_sanitizer(self, server: str, tool: str, args: list[TaintedValue]) -> bool:
        # Placeholder: real impl runs schema/allowlist/regex over the sanitized output
        # and confirms the injected span is absent. Returning False here forces fail-closed.
        return False
