# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-quarantined-argument-is-laundered-through-a-tool-s-return-value.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-provenance-when-a-quarantined-argument-is-laundered-through-a-tool-s-return-value.warrant.json
# Markdown SHA-256:   326feb0c9537e57bdab7cf8a56d1b1beb069ccbe8fdb4e3ef2acb1d12ba51e46
# Code AST SHA-256:   972af0dcb8d152b34b1fd5dd51a64bdf728267221318b628a0bdbf199c94d2c4
# Verified Classes:   TaintLaunderingError, Labeled, ToolSpec
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a tool would drop taint labels from its return channel
    without an audited declassification contract."""
    pass


@dataclass(frozen=True)
class Labeled:
    value: str
    labels: FrozenSet[str] = field(default_factory=frozenset)


@dataclass(frozen=True)
class ToolSpec:
    name: str
    return_taint: str = "propagate"          # "propagate" | "drop"
    declassify_contract: str | None = None  # required when return_taint == "drop"


def invoke_tool(spec: ToolSpec, args: list[Labeled], impl) -> Labeled:
    union = frozenset().union(*(a.labels for a in args))

    if spec.return_taint == "drop":
        if union and spec.declassify_contract is None:
            # A drop-mode tool receiving tainted input is a laundering primitive.
            raise TaintLaunderingError(
                f"tool '{spec.name}' would drop labels {sorted(union)} "
                f"from its return channel with no declassify contract"
            )
        if union and spec.declassify_contract is not None:
            # Contract present: still must be machine-checked elsewhere; here we
            # only permit an explicitly declared strip.
            return Labeled(impl(*[a.value for a in args]), frozenset())
        return Labeled(impl(*[a.value for a in args]), frozenset())

    # Default: return-taint closure — output inherits the union of input labels.
    return Labeled(impl(*[a.value for a in args]), union)


def sink_gate(arg: Labeled, sink_name: str) -> None:
    if arg.labels:
        raise TaintLaunderingError(
            f"sink '{sink_name}' refused argument carrying labels {sorted(arg.labels)}"
        )


# --- reproduction of the failure ---
tainted = Labeled("/etc/cron.d/x", frozenset({"tainted:web"}))

# A pure tool registered with the legacy default that drops labels:
legacy_norm = ToolSpec(name="normalize_path", return_taint="drop")
try:
    out = invoke_tool(legacy_norm, [tainted], lambda s: s)
    sink_gate(out, "delete_file")          # would pass under the buggy runtime
except TaintLaunderingError as e:
    print("blocked:", e)

# With closure default, the sink refuses:
safe_norm = ToolSpec(name="normalize_path")  # return_taint="propagate"
out = invoke_tool(safe_norm, [tainted], lambda s: s)
try:
    sink_gate(out, "delete_file")
except TaintLaunderingError as e:
    print("blocked:", e)
