# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-tool-that-returns-a-derived-value-rather-than-the-tainted-bytes.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-injected-taint-through-a-tool-that-returns-a-derived-value-rather-than-the-tainted-bytes.warrant.json
# Markdown SHA-256:   eb369c914078e99198afc80daf0dcd46a60a6384f83d51ecd604fc33652b64c7
# Code AST SHA-256:   a2530beaf7ecf9b18606c5c3aefb2b81644024d6ebc695538c3b497ff5ef0365
# Verified Classes:   TaintLaunderingError, ToolClass, Label, ToolSpec
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TaintLaunderingError(RuntimeError):
    """Raised when a derived tool output would lose inherited taint."""


class ToolClass(Enum):
    TRANSPARENT = "transparent"      # output contains argument bytes; overlap is sound
    OPAQUE_DERIVED = "opaque"        # output is a function of argument values


@dataclass(frozen=True)
class Label:
    tainted: bool
    sources: frozenset = field(default_factory=frozenset)

    def join(self, other: "Label") -> "Label":
        return Label(self.tainted or other.tainted, self.sources | other.sources)


CLEAN = Label(False)


@dataclass
class ToolSpec:
    name: str
    cls: ToolClass
    read_set: frozenset  # argument names the implementation actually reads


REGISTRY = {
    "string_contains": ToolSpec("string_contains", ToolClass.OPAQUE_DERIVED, frozenset({"text", "needle"})),
    "count_matches":   ToolSpec("count_matches",   ToolClass.OPAQUE_DERIVED, frozenset({"text", "pattern"})),
    "echo":            ToolSpec("echo",            ToolClass.TRANSPARENT,    frozenset({"text"})),
}


def label_tool_output(spec: ToolSpec, arg_labels: dict, output: Any) -> Label:
    if spec.cls is ToolClass.TRANSPARENT:
        # overlap propagation is sound only for transparent tools
        return CLEAN.join(*arg_labels.values()) if arg_labels else CLEAN

    # OPAQUE_DERIVED: output is value-dependent on every read-set argument
    missing = spec.read_set - arg_labels.keys()
    if missing:
        raise TaintLaunderingError(
            f"tool {spec.name!r} reads {sorted(missing)} but no label supplied; "
            f"cannot compute dependency-closure label"
        )
    result = CLEAN
    for name in spec.read_set:
        result = result.join(arg_labels[name])
    return result


def guard_control_flow(condition_label: Label, authorizes_effect: bool) -> None:
    """A tainted value used to gate a privileged effect is a control-flow taint sink."""
    if authorizes_effect and condition_label.tainted:
        raise TaintLaunderingError(
            "control-flow taint: derived value with inherited taint gates a privileged "
            f"effect (sources={sorted(condition_label.sources)})"
        )


# --- reproduction of the observed failure ---
untrusted = Label(True, frozenset({"email_body"}))
spec = REGISTRY["string_contains"]
cond_label = label_tool_output(spec, {"text": untrusted, "needle": CLEAN}, True)
# cond_label.tainted is True under dependency-closure; overlap propagation would have said CLEAN.
guard_control_flow(cond_label, authorizes_effect=True)  # raises
