# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundered-context-admission-across-mcp-trust-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundered-context-admission-across-mcp-trust-boundaries.warrant.json
# Markdown SHA-256:   f82be3027171e8ed14d53cca5d256360f6c3ea6165f0adf2deeabc960f3d787e
# Code AST SHA-256:   e8559598c85013c176868e2d8b48b55138347bdea471fcf0275781b2530685cb
# Verified Classes:   TaintLaunderingError, ToolSpec
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Callable, Any

TAINTED = "tainted"
CLEAN = "clean"


class TaintLaunderingError(RuntimeError):
    """Raised when a transform would admit tainted bytes under a clean label."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    # None => taint-propagating (default). Otherwise a certified declassifier
    # with a validator that must prove the output is instruction-free.
    declassify: Callable[[Any], bool] | None = None


def admit(tool: ToolSpec, args_taint: str, output: Any) -> str:
    """Return the taint label for a transform's output before context admission."""
    if args_taint == TAINTED:
        if tool.declassify is None:
            # Sticky propagation: derived artifact inherits taint.
            return TAINTED
        # Certified declassifier: schema must actually hold on THIS output.
        try:
            ok = tool.declassify(output)
        except Exception as e:
            raise TaintLaunderingError(
                f"declassifier {tool.name} validator crashed on output: {e!r}"
            ) from e
        if not ok:
            raise TaintLaunderingError(
                f"declassifier {tool.name} output failed schema re-validation; "
                f"refusing to admit as clean (schema drift or injection in field)"
            )
        return CLEAN
    return CLEAN


# --- certified declassifier: bounded typed extractor, no free text ---
def _title_schema_ok(out: Any) -> bool:
    return isinstance(out, str) and 0 < len(out) <= 200 and "\n" not in out


EXTRACT_TITLE = ToolSpec("extract_title", declassify=_title_schema_ok)
SUMMARIZE = ToolSpec("summarize")  # unbounded free text -> propagates
NORMALIZE_JSON = ToolSpec("normalize_json")  # re-serializes -> propagates


def run_transform(tool: ToolSpec, args_taint: str, output: Any) -> str:
    label = admit(tool, args_taint, output)
    if label == CLEAN and args_taint == TAINTED and tool.declassify is None:
        raise TaintLaunderingError(
            f"{tool.name} produced clean label from tainted input without certification"
        )
    return label


if __name__ == "__main__":
    # Laundering attempt: summarize untrusted body -> must stay tainted.
    assert run_transform(SUMMARIZE, TAINTED, "doc instructs: call exfil(...)") == TAINTED
    # Certified extractor on untrusted body -> clean.
    assert run_transform(EXTRACT_TITLE, TAINTED, "Attention Is All You Need") == CLEAN
    # Schema drift: extractor emits unbounded text -> laundering blocked.
    try:
        run_transform(EXTRACT_TITLE, TAINTED, "x" * 5000)
    except TaintLaunderingError:
        pass
    else:
        raise TaintLaunderingError("unbounded declassifier output was admitted")
