# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-prompt-injection-taint-across-a-tool-boundary-rather-than-clearing-it-at-the-return-edge.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-prompt-injection-taint-across-a-tool-boundary-rather-than-clearing-it-at-the-return-edge.warrant.json
# Markdown SHA-256:   e26936298f043970d6cb58a6e0d0e5b74d747a7d8f9909e0fa09d1fbd54019f3
# Code AST SHA-256:   d7d3f529487f6c7a23649483fd29977c46befb2c2bb381850814235159d87bbc
# Verified Classes:   TaintLaunderingError, Label
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a tool return edge would clear taint that must propagate."""
    pass


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

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


def tool_return_label(
    tool_name: str,
    arg_labels: list[Label],
    tool_is_pure_producer: bool,
    out_of_band_validated: bool,
) -> Label:
    """Compute the label at a tool return edge.

    Conservative default: an LLM-backed or opaque tool is NOT a pure
    producer, so its output inherits the join of its tainted inputs.
    """
    input_closure = Label(False, frozenset())
    for lab in arg_labels:
        input_closure = input_closure.join(lab)

    if tool_is_pure_producer:
        return Label(False, frozenset())

    if out_of_band_validated and not input_closure.tainted:
        return Label(False, frozenset())

    if out_of_band_validated:
        # Validation succeeded against a trusted registry; discharge.
        return Label(False, frozenset())

    if input_closure.tainted:
        return Label(True, input_closure.sources | {f"tool:{tool_name}"})

    return Label(False, frozenset())


def insert_into_context(
    slot_is_actionable: bool,
    proposed_label: Label,
    cleared_label: Label,
) -> Label:
    """Reject a return edge that clears taint on an actionable sink."""
    if slot_is_actionable and proposed_label.tainted and not cleared_label.tainted:
        raise TaintLaunderingError(
            f"return edge cleared taint {sorted(proposed_label.sources)} "
            f"into actionable slot; propagation required"
        )
    return cleared_label


# --- exercise the invariant ---
poisoned_doc = Label(True, frozenset({"fetch:doc#footnote"}))

# Summarizer consumes tainted doc, is NOT a pure producer, no validation.
summary_label = tool_return_label(
    "summarize",
    arg_labels=[poisoned_doc],
    tool_is_pure_producer=False,
    out_of_band_validated=False,
)
assert summary_label.tainted, "summarizer output must inherit input taint"

# A naive edge tries to clear it because the summarizer is 'trusted'.
try:
    insert_into_context(
        slot_is_actionable=True,
        proposed_label=summary_label,
        cleared_label=Label(False, frozenset()),
    )
except TaintLaunderingError as e:
    print(f"contained: {e}")

# Pure producer: clock tool, no tainted input, clears soundly.
clock_label = tool_return_label(
    "now", arg_labels=[], tool_is_pure_producer=True, out_of_band_validated=False
)
assert not clock_label.tainted
