# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-taint-a-value-after-declassification-and-why-does-label-laundering-through-tool-output-defeat-single-pass-taint-tracking.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-taint-a-value-after-declassification-and-why-does-label-laundering-through-tool-output-defeat-single-pass-taint-tracking.warrant.json
# Markdown SHA-256:   b7ffc7c190593f5b71b52fb74ffbc5b534fb23b9e052d960e06cc2815e994c41
# Code AST SHA-256:   fa21baebda73ccf50290a5744844986953307f55de31e960055217c449dc1000
# Verified Classes:   TaintLaunderingError, Value, ToolResult
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

# Label lattice: a set of provenance tags; join is set union.
Label = FrozenSet[str]

def join(*labels: Label) -> Label:
    out: set[str] = set()
    for l in labels:
        out |= l
    return frozenset(out)

TRUSTED: Label = frozenset({"trusted"})
UNTRUSTED_RETRIEVED: Label = frozenset({"untrusted:retrieved"})
UNTRUSTED_PEER: Label = frozenset({"untrusted:peer"})


class TaintLaunderingError(RuntimeError):
    """Raised when a value crosses a trust boundary without a principal-owned declassification."""


@dataclass
class Value:
    payload: str
    label: Label


@dataclass
class ToolResult:
    payload: str
    label: Label


def emit_tool_output(
    tool_name: str,
    args: dict[str, Value],
    context_label: Label,
    tool_config_label: Label,
    raw_output: str,
) -> ToolResult:
    """
    Emission-join invariant: output label = join(args, context, tool_config).
    The context_label is the join over the model's attended window at call time,
    NOT just the labels of the extracted arguments. Omitting it is the laundering bug.
    """
    if context_label is None:
        raise TaintLaunderingError(
            f"tool {tool_name}: context_label missing; cannot compute emission join"
        )
    out_label = join(
        context_label,
        tool_config_label,
        *(v.label for v in args.values()),
    )
    return ToolResult(payload=raw_output, label=out_label)


def send_to_peer(
    sender_context_label: Label,
    message: Value,
    receiver_requires: Label,
) -> Value:
    """
    Handoff-effective-label invariant: the message carries the sender's effective
    label (join of sender context and message label), not the sender's identity.
    """
    effective = join(sender_context_label, message.label)
    if not receiver_requires.issubset(effective):
        # Receiver demands trusted input but sender is tainted: refuse, do not relabel.
        raise TaintLaunderingError(
            f"handoff blocked: receiver requires {set(receiver_requires)}, "
            f"effective sender label is {set(effective)}"
        )
    return Value(payload=message.payload, label=effective)


def write_summary(summary: Value, sink_requires: Label = TRUSTED) -> str:
    """A sensitive sink. Requires a label that dominates the sink requirement."""
    if not sink_requires.issubset(summary.label):
        raise TaintLaunderingError(
            f"summary write blocked: sink requires {set(sink_requires)}, "
            f"value label is {set(summary.label)}; declassify with a named principal first"
        )
    return summary.payload


# Reproduction of the observed trace.
if __name__ == "__main__":
    user_id = Value(payload="u_42", label=TRUSTED)              # extracted from trusted turn
    retrieved = Value(payload="...injected instruction...", label=UNTRUSTED_RETRIEVED)

    # Model chose export_user_data while attending to the tainted retrieval.
    context_at_call = join(retrieved.label, TRUSTED)            # = UNTRUSTED_RETRIEVED

    result = emit_tool_output(
        tool_name="export_user_data",
        args={"user_id": user_id},
        context_label=context_at_call,
        tool_config_label=TRUSTED,
        raw_output='{"ssn": "...", "email": "..."}',
    )
    # result.label == UNTRUSTED_RETRIEVED  -> cannot be relabeled trusted.

    summary = Value(payload="Summary: " + result.payload, label=result.label)
    try:
        write_summary(summary)  # raises: sink requires trusted, value is tainted
    except TaintLaunderingError as e:
        print("contained:", e)

    # Handoff variant: tainted sender cannot pass as trusted peer.
    try:
        send_to_peer(
            sender_context_label=UNTRUSTED_RETRIEVED,
            message=Value(payload="please summarize", label=TRUSTED),
            receiver_requires=TRUSTED,
        )
    except TaintLaunderingError as e:
        print("handoff contained:", e)
