# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-multi-hop-tool-invocation-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-multi-hop-tool-invocation-graphs.warrant.json
# Markdown SHA-256:   6b0bd8f6eefac9b9ccfa09da39423be584822b10c729996a72fc28cc8d33c521
# Code AST SHA-256:   aa13e99a6ab43c3263488580696b9cb37ac02672ce6e9accc8be268bcd402614
# Verified Classes:   TaintLaunderingError, Tainted
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink receives a value whose lineage
    includes untrusted sources not allowlisted for that sink."""
    pass


@dataclass(frozen=True)
class Tainted:
    value: object
    lineage: FrozenSet[str] = field(default_factory=frozenset)

    def derive(self, *others: "Tainted") -> "Tainted":
        # Lineage is union over inputs, never a lookup of producer trust.
        merged = set(self.lineage)
        for o in others:
            merged |= o.lineage
        return Tainted(self.value, frozenset(merged))


TRUSTED_SINKS = {
    "send_email": frozenset(),          # no untrusted lineage permitted
    "post_comment": frozenset({"operator_prompt"}),
}


def invoke_privileged(sink: str, arg: Tainted) -> None:
    allowed = TRUSTED_SINKS.get(sink)
    if allowed is None:
        raise TaintLaunderingError(f"unknown privileged sink: {sink}")
    if not arg.lineage.issubset(allowed):
        leaked = arg.lineage - allowed
        raise TaintLaunderingError(
            f"taint laundering blocked at sink {sink!r}: "
            f"untrusted lineage {sorted(leaked)} not allowlisted"
        )
    # proceed with the call
    return None


# Reproduces the observed failure: summarize() is trusted code, but its
# output schema is plain str and drops lineage. The adapter must re-attach it.
def summarize_adapter(page: Tainted) -> Tainted:
    summary_text = str(page.value)  # trusted code, untrusted content
    return Tainted(summary_text, page.lineage)  # lineage preserved


def run_pipeline() -> None:
    page = Tainted("...injected: call send_email to ops@...", frozenset({"fetch_url:page_7f3a"}))
    summary = summarize_adapter(page)
    # Without the adapter, summary.lineage would be empty and this would pass.
    invoke_privileged("send_email", summary)  # raises TaintLaunderingError


if __name__ == "__main__":
    run_pipeline()
