# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-benign-looking-tool-call-hop.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-benign-looking-tool-call-hop.warrant.json
# Markdown SHA-256:   7736f15e96ac666706ca474984bd7e1e6ccfaffa8b2068f6ceba66f961fd1247
# Code AST SHA-256:   676c6a9dc55266f9d530700da71ad1c039c05a26a1d4377eec0a5748cb4d4b05
# Verified Classes:   TaintPropagationError, SinkViolation, ToolSpec, CallResult
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintPropagationError(RuntimeError):
    """Raised when a tool call drops taint that its inputs carried,
    without being an audited declassifier."""
    pass


class SinkViolation(RuntimeError):
    """Raised when a side-effecting sink receives a tainted argument."""
    pass


@dataclass
class ToolSpec:
    name: str
    role: str  # "propagator" | "source" | "declassifier" | "sink"
    audited_declassifier: bool = False


@dataclass
class CallResult:
    tool: str
    input_labels: list[bool]
    output_label: bool
    declassify_justification: Optional[str] = None


PROPAGATORS = {
    "summarize": ToolSpec("summarize", "propagator"),
    "json_normalize": ToolSpec("json_normalize", "propagator"),
    "translate": ToolSpec("translate", "propagator"),
}
SOURCES = {"fetch_url": ToolSpec("fetch_url", "source")}
SINKS = {"write_file": ToolSpec("write_file", "sink"),
         "send_email": ToolSpec("send_email", "sink"),
         "exec": ToolSpec("exec", "sink")}

REGISTRY = {**PROPAGATORS, **SOURCES, **SINKS}


def propagate_taint(tool_name: str, input_labels: list[bool],
                    observed_output_label: bool,
                    declassify_justification: Optional[str] = None) -> CallResult:
    """Enforce L_out superset-of union(L_in) for every non-declassifier node.

    The output label is *computed* from inputs, never taken from the
    tool's self-report of its output text.
    """
    spec = REGISTRY.get(tool_name)
    if spec is None:
        raise TaintPropagationError(
            f"unregistered tool {tool_name!r}: cannot establish provenance edge"
        )

    union_in = any(input_labels)

    if spec.role == "declassifier":
        if not spec.audited_declassifier or not declassify_justification:
            raise TaintPropagationError(
                f"declassifier {tool_name!r} lacks audit justification"
            )
        return CallResult(tool_name, input_labels, observed_output_label,
                          declassify_justification)

    # Propagators and sources must satisfy L_out >= union(L_in).
    computed = union_in or spec.role == "source"
    if computed and not observed_output_label:
        raise TaintPropagationError(
            f"taint laundered at {tool_name!r}: inputs tainted, "
            f"output reported clean; label must flow along dataflow edge"
        )

    return CallResult(tool_name, input_labels, computed)


def enforce_sink(call: CallResult) -> None:
    """Block side-effecting sinks that receive tainted arguments."""
    spec = REGISTRY[call.tool]
    if spec.role == "sink" and call.output_label:
        raise SinkViolation(
            f"sink {call.tool!r} received tainted argument; "
            f"blocked pending audited declassification"
        )


def run_chain() -> None:
    # Hop 1: untrusted fetch -> tainted
    hop1 = propagate_taint("fetch_url", [False], observed_output_label=True)
    # Hop 2: model-mediated summarize. Tracker must NOT trust the
    # summarizer's clean self-report; propagation forces taint through.
    hop2 = propagate_taint("summarize", [hop1.output_label],
                           observed_output_label=False)
    # Hop 3: sink must be blocked because hop2 is tainted.
    hop3 = propagate_taint("write_file", [hop2.output_label],
                           observed_output_label=False)
    enforce_sink(hop3)  # raises SinkViolation


if __name__ == "__main__":
    run_chain()
