# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-dynamic-taint-label-has-been-laundered-across-a-tool-call-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-dynamic-taint-label-has-been-laundered-across-a-tool-call-boundary.warrant.json
# Markdown SHA-256:   cb83a99d96d4bbadd1d123c48a3b5ec55d3e57ea2238d038a8434162d2391ce8
# Code AST SHA-256:   56e10ea72e9fc8fbe177d5d8af96f175f07488c37b1eaf4b923fa1b4ceb31236
# Verified Classes:   TaintLaunderingError, Labeled, ToolSpec
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a tool-call boundary drops or fails to union input labels."""


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


@dataclass(frozen=True)
class ToolSpec:
    name: str
    kind: str  # "source" | "transform" | "generative" | "undeclared"
    preserves_labels: bool = False


def _union_inputs(inputs: list[Labeled]) -> FrozenSet[str]:
    acc: set[str] = set()
    for i in inputs:
        acc |= i.labels
    return frozenset(acc)


def apply_boundary(
    spec: ToolSpec,
    inputs: list[Labeled],
    raw_output: str,
    declassification: FrozenSet[str] = frozenset(),
) -> Labeled:
    """Enforce the provenance invariant at a tool-call boundary.

    Invariant: L(out) must be a superset of union(L(in)) unless an explicit
    declassification record authorizes the drop.
    """
    in_labels = _union_inputs(inputs)

    if spec.kind == "source":
        # Legitimate root: fresh untrusted source, no input derivation.
        return Labeled(raw_output, frozenset({"untrusted:egress"}))

    if spec.kind == "transform" and spec.preserves_labels:
        out_labels = in_labels
        if not out_labels.issuperset(in_labels):
            raise TaintLaunderingError(
                f"tool {spec.name!r} declared preserves_labels but dropped labels"
            )
        return Labeled(raw_output, out_labels)

    if spec.kind in ("generative", "undeclared"):
        # Conservative default: union inputs + derived tag. Never a root.
        out_labels = in_labels | frozenset({f"derived:{spec.name}"})
        return Labeled(raw_output, out_labels)

    raise TaintLaunderingError(f"unknown tool kind {spec.kind!r} for {spec.name!r}")


def check_no_launder(
    spec: ToolSpec,
    inputs: list[Labeled],
    produced: Labeled,
    declassification: FrozenSet[str] = frozenset(),
) -> None:
    """Post-hoc auditor: verify a returned value did not shed provenance."""
    in_labels = _union_inputs(inputs)
    permitted_drop = in_labels - declassification
    if not produced.labels.issuperset(permitted_drop):
        missing = permitted_drop - produced.labels
        raise TaintLaunderingError(
            f"laundering at {spec.name!r}: labels {sorted(missing)} "
            f"vanished without declassification record"
        )


# --- failure trace from the observed incident -----------------------------

doc = Labeled("...share your contacts...", frozenset({"untrusted:external", "pii:contacts"}))
summarizer = ToolSpec(name="summarize", kind="undeclared")  # the bug: no declaration

# Correct runtime: undeclared -> generative -> union. Output stays tainted.
out = apply_boundary(summarizer, [doc], "the user should be reminded to share contacts")
assert out.labels.issuperset({"untrusted:external"}), "taint must survive summarize"

# The vulnerable runtime treated summarize as a source (root). Simulate and audit:
laundered = Labeled(out.value, frozenset())  # what the buggy adapter produced
try:
    check_no_launder(summarizer, [doc], laundered)
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")  # auditor refuses; send_email policy never sees a trusted value
