# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-multi-hop-mcp-tool-chain-before-the-sink-executes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-multi-hop-mcp-tool-chain-before-the-sink-executes.warrant.json
# Markdown SHA-256:   15b31422239a3272877b620b64faa093129303ece58126dab35518b5abfe0c13
# Code AST SHA-256:   b9941404ff793f2376d9f9112fede1441e30f86669ae76a49829bf8fbffab2d2
# Verified Classes:   TaintLaunderingError, TrustClass, Provenance, TaskContext
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a sensitive sink would execute on tainted context or provenance."""


class TrustClass(str, Enum):
    TRUSTED = "trusted"
    UNTRUSTED = "untrusted"


# Transforms that are provably lossless AND do not emit free-form text may declassify.
# A markdown normalizer is deliberately absent: it interprets and emits free-form strings.
LOSSless_DECLASSIFY_ALLOWLIST: FrozenSet[str] = frozenset({"base64_decode", "gzip_decompress"})

# Sinks that must never execute under tainted provenance or tainted context.
SENSITIVE_SINKS: FrozenSet[str] = frozenset(
    {"write_workspace_file", "read_file", "run_shell", "http_egress"}
)


@dataclass(frozen=True)
class Provenance:
    sources: FrozenSet[str] = frozenset()
    trust: TrustClass = TrustClass.TRUSTED

    def union(self, other: "Provenance") -> "Provenance":
        trust = (
            TrustClass.UNTRUSTED
            if TrustClass.UNTRUSTED in (self.trust, other.trust)
            else TrustClass.TRUSTED
        )
        return Provenance(self.sources | other.sources, trust)

    def is_tainted(self) -> bool:
        return self.trust is TrustClass.UNTRUSTED


@dataclass
class TaskContext:
    context_provenance: Provenance = field(default_factory=Provenance)
    declassification_warrants: set[str] = field(default_factory=set)

    def absorb_response(self, source: str, trust: TrustClass) -> None:
        self.context_provenance = self.context_provenance.union(
            Provenance(frozenset({source}), trust)
        )


def apply_transform(
    transform: str,
    input_prov: Provenance,
    output_schema_is_freeform: bool,
) -> Provenance:
    """A transform may declassify only if lossless AND its output schema is not free-form."""
    if transform in LOSSless_DECLASSIFY_ALLOWLIST and not output_schema_is_freeform:
        return Provenance(frozenset(), TrustClass.TRUSTED)
    # Otherwise provenance propagates unchanged: this hop is a laundering surface, not a reset.
    return input_prov


def guard_sink(
    sink: str,
    arg_provenance: Provenance,
    ctx: TaskContext,
    warrant_id: str | None = None,
) -> None:
    """Enforce taint-aware sandboxing at a sensitive sink. Raises on violation."""
    if sink not in SENSITIVE_SINKS:
        return

    if arg_provenance.is_tainted():
        raise TaintLaunderingError(
            f"sink={sink} blocked: argument provenance tainted "
            f"sources={sorted(arg_provenance.sources)}"
        )

    if ctx.context_provenance.is_tainted():
        if warrant_id is None or warrant_id not in ctx.declassification_warrants:
            raise TaintLaunderingError(
                f"sink={sink} blocked: tainted-context execution "
                f"context_sources={sorted(ctx.context_provenance.sources)} "
                f"warrant={warrant_id!r} not granted"
            )


# --- Replay of the observed chain -------------------------------------------

def replay_laundering_chain() -> None:
    ctx = TaskContext()

    # Hop 1: untrusted fetch enters context.
    ctx.absorb_response("fetch_url", TrustClass.UNTRUSTED)
    fetched_prov = Provenance(frozenset({"fetch_url"}), TrustClass.UNTRUSTED)

    # Hop 2: parse_markdown normalizes; free-form output schema => NO declassification.
    parsed_prov = apply_transform(
        "parse_markdown", fetched_prov, output_schema_is_freeform=True
    )
    assert parsed_prov.is_tainted(), "normalizer must not reset provenance"

    # Hop 3: sink with clean-looking args but tainted context and no warrant.
    guard_sink("write_workspace_file", Provenance(), ctx)  # raises


if __name__ == "__main__":
    try:
        replay_laundering_chain()
    except TaintLaunderingError as exc:
        print(f"BLOCKED: {exc}")
