# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-treat-taint-laundering-through-reversible-transforms-when-sandboxing-exfiltration-sinks.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-treat-taint-laundering-through-reversible-transforms-when-sandboxing-exfiltration-sinks.warrant.json
# Markdown SHA-256:   b33bbcac24f51a21b5cc6e0cca940f09eb2fa3f57e4373072f116d80ce2867b1
# Code AST SHA-256:   86bd4c0a674d6e79fb9dcd8347b5454bcc0284bc65dfc74da413447832a3185b
# Verified Classes:   TaintLaunderingError, Provenance, TaintGraph
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class TaintLaunderingError(RuntimeError):
    """Raised when a tainted value reaches an exfiltration sink via an
    unlabeled transform (encoding, slicing, summarization, etc.)."""


@dataclass
class Provenance:
    node_id: str
    tainted: bool
    ancestors: frozenset = field(default_factory=frozenset)


class TaintGraph:
    def __init__(self) -> None:
        self._nodes: dict = {}

    def ingest(self, node_id: str, tainted: bool) -> Provenance:
        p = Provenance(node_id=node_id, tainted=tainted,
                       ancestors=frozenset({node_id}) if tainted else frozenset())
        self._nodes[node_id] = p
        return p

    def derive(self, src: Provenance, out_id: str) -> Provenance:
        # Identity/pure-transform propagation: ancestors carry through.
        p = Provenance(node_id=out_id, tainted=src.tainted,
                       ancestors=src.ancestors | {out_id})
        self._nodes[out_id] = p
        return p

    def has_tainted_ancestor(self, p: Provenance) -> bool:
        return any(self._nodes[a].tainted for a in p.ancestors)


# Tool registry: every tool MUST declare how taint flows through it.
TRANSFORMS: dict = {
    "identity":    lambda src, out: src,          # passthrough
    "encode":      lambda src, out: src,          # base64/hex/url: propagate
    "slice":       lambda src, out: src,          # chunking: propagate
    "summarize":   lambda src, out: src,          # semantic: propagate (conservative)
    "constant":    lambda src, out: None,         # genuinely fresh value
}


def call_tool(graph: TaintGraph, tool: str, src: Provenance, out_id: str) -> Provenance:
    if tool not in TRANSFORMS:
        raise TaintLaunderingError(f"tool {tool!r} has no taint-transfer declaration")
    inherited = TRANSFORMS[tool](src, out_id)
    if inherited is None:
        return graph.ingest(out_id, tainted=False)
    return graph.derive(inherited, out_id)


def egress(graph: TaintGraph, value: Provenance, sink: str) -> None:
    if graph.has_tainted_ancestor(value):
        raise TaintLaunderingError(
            f"blocked egress to {sink!r}: value {value.node_id!r} has tainted "
            f"ancestors {sorted(value.ancestors)}"
        )
    # ... actual network write ...


def demo() -> None:
    g = TaintGraph()
    retrieved = g.ingest("chunk_42", tainted=True)
    encoded = call_tool(g, "encode", retrieved, "b64_out")
    try:
        egress(g, encoded, "http_post")
    except TaintLaunderingError as exc:
        print("caught:", exc)  # content guard would have missed this


if __name__ == "__main__":
    demo()
