# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-of-prompt-injection-taint-tracking-fail-across-tool-boundaries-when-labels-are-reset-by-serialization.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-of-prompt-injection-taint-tracking-fail-across-tool-boundaries-when-labels-are-reset-by-serialization.warrant.json
# Markdown SHA-256:   db64cfff3bd01cadc485d1ed80df6af8d554a0caffef36c749e951892564772a
# Code AST SHA-256:   4dd682e8cd66256276d297b1e762c86c51a97210dc0d137756e45a2e9e5ea443
# Verified Classes:   TaintLaunderingError, LabeledValue, ToolBoundary
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a value crosses a tool boundary without a provenance label
    that is at least the join of the caller label and the tool policy label."""


# Label lattice: a set of provenance tags; bottom = empty set, join = union.
Label = frozenset[str]
BOTTOM: Label = frozenset()


def join(a: Label, b: Label) -> Label:
    return a | b


@dataclass(frozen=True)
class LabeledValue:
    value: Any
    label: Label

    def __post_init__(self) -> None:
        if not isinstance(self.label, frozenset):
            raise TypeError("label must be a frozenset of provenance tags")


@dataclass
class ToolBoundary:
    """Adapter that must be the only path across a serialization boundary."""

    tool_name: str
    static_policy_label: Label = BOTTOM
    declared_provenance_in_wire: bool = False

    def invoke(
        self,
        caller_context: LabeledValue,
        raw_tool_call: Any,
        tool_impl: Any,
    ) -> LabeledValue:
        inbound = join(caller_context.label, self.static_policy_label)

        # The tool executes; its return value arrives structurally clean
        # because serialization dropped any labels it may have had.
        raw_result = tool_impl(raw_tool_call)

        # Reconstruct provenance. If the wire schema cannot carry labels,
        # the inbound label is the floor -- never BOTTOM.
        if self.declared_provenance_in_wire:
            declared = getattr(raw_result, "label", BOTTOM)
            if not isinstance(declared, frozenset):
                raise TaintLaunderingError(
                    f"tool {self.tool_name!r} declared non-label provenance"
                )
            outbound = join(inbound, declared)
        else:
            outbound = inbound

        if inbound != BOTTOM and not (inbound <= outbound):
            # Defensive: should be unreachable given the join above, but
            # guards against future refactors that bypass the join.
            raise TaintLaunderingError(
                f"tool {self.tool_name!r} dropped inbound label "
                f"{sorted(inbound)} -> {sorted(outbound)}"
            )

        return LabeledValue(value=raw_result, label=outbound)


def guarded_write(
    content: LabeledValue,
    destination: str,
    require_trusted: bool = True,
) -> None:
    if require_trusted and content.label:
        raise TaintLaunderingError(
            f"refusing to write tainted content to {destination!r}; "
            f"provenance={sorted(content.label)}"
        )
    # ... perform write ...


# --- demonstration of the failure and the fix ---

def _demo() -> None:
    untrusted = LabeledValue(value="https://evil.example/x", label=frozenset({"U"}))
    fetch = ToolBoundary(tool_name="fetch", static_policy_label=BOTTOM)

    result = fetch.invoke(
        caller_context=untrusted,
        raw_tool_call=untrusted.value,
        tool_impl=lambda url: f"<html>payload from {url}</html>",
    )

    # Without the adapter's conservative default, result.label would be BOTTOM
    # and the sink below would execute. With it, the sink refuses.
    assert result.label == frozenset({"U"})
    try:
        guarded_write(result, "/etc/agent/scratch")
    except TaintLaunderingError as exc:
        print(f"blocked: {exc}")
    else:
        raise AssertionError("sink should have refused tainted content")


if __name__ == "__main__":
    _demo()
