# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-trusted-tool-the-transitive-labeling-failure-in-multi-hop-invocation-graphs.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-trusted-tool-the-transitive-labeling-failure-in-multi-hop-invocation-graphs.warrant.json
# Markdown SHA-256:   07409fdcd0274bc907b15a3aae12c6a2cf34f6b8119e719836642d7bb4777784
# Code AST SHA-256:   9f281db874c796881c527601eb609b55d2b25d7b9ffccdfcb4ed57d8982c2aa2
# Verified Classes:   TaintLaunderingError, Provenance
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a side-effecting call is reached through a laundered taint path."""


@dataclass
class Provenance:
    label: str                      # "none" | "external" | "derived"
    root: Optional[str] = None      # originating untrusted source, if any
    via: list = field(default_factory=list)  # re-labeling nodes traversed


def propagate_decision_taint(
    input_prov: Provenance,
    node: str,
    output_trust_tier: str,         # "trusted" | "untrusted"
) -> Provenance:
    """Label a tool output given that its *selection* may have been tainted.

    Value-taint alone would return Provenance("none") for a trusted tool whose
    output contains no external text. Decision-taint instead carries the
    derivation forward, so the output inherits residual taint.
    """
    if input_prov.label in ("external", "derived"):
        # The tool was chosen by tainted reasoning. Its output is derived,
        # even if the tool itself is trusted and the output bytes are clean.
        return Provenance(
            label="derived",
            root=input_prov.root,
            via=input_prov.via + [node],
        )
    return Provenance(label="none")


def guard_sink(
    sink: str,
    payload_prov: Provenance,
    discharge_token: Optional[str],
    is_out_of_band_verifier: bool,
) -> None:
    """Bound the laundering: side-effecting sinks require a clean chain or a
    discharge issued by a verifier outside the agent's invocation graph."""
    if payload_prov.label == "none":
        return
    if discharge_token is None:
        raise TaintLaunderingError(
            f"sink={sink!r} reached with taint root={payload_prov.root!r} "
            f"via={payload_prov.via!r}; no discharge token presented"
        )
    if not is_out_of_band_verifier:
        raise TaintLaunderingError(
            f"sink={sink!r}: discharge token for root={payload_prov.root!r} "
            f"was issued inside the agent invocation graph; verifier must be "
            f"out-of-band (human, separate principal, or deterministic check)"
        )


# --- Reproduce the three-hop trace -------------------------------------------
# hop 1: web_fetch returns external text
p1 = Provenance(label="external", root="web_fetch")
# hop 2: planner selects kb_lookup (trusted tool) from tainted reasoning
p2 = propagate_decision_taint(p1, node="planner", output_trust_tier="trusted")
p3 = propagate_decision_taint(p2, node="kb_lookup", output_trust_tier="trusted")
# hop 3: email_send is a side-effecting sink
guard_sink("email_send", p3, discharge_token=None, is_out_of_band_verifier=False)
# -> raises TaintLaunderingError; the naive value-taint rule would have let it pass
