# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-when-a-tool-boundary-re-serializes-its-own-output.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-taint-labels-when-a-tool-boundary-re-serializes-its-own-output.warrant.json
# Markdown SHA-256:   44bbcfa431679c12674562b32d53e41bedf45ba972b8fb9f7abe08fe489b6cac
# Code AST SHA-256:   dfe15ede46d2db449f3a2e022859cd6d959addb0e90bfc8b1aff4f4afea2b6c5
# Verified Classes:   TaintLaunderingError, Label, ToolManifest
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a tool output would drop inbound taint without a verified independence declaration."""


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

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


TRUSTED = Label(frozenset(), False)


def join_all(labels: list[Label]) -> Label:
    acc = TRUSTED
    for l in labels:
        acc = acc.join(l)
    return acc


@dataclass
class ToolManifest:
    name: str
    output_taint: str  # "independent" | "derived"
    signed: bool


def invoke_tool(manifest: ToolManifest, args: dict[str, tuple[Any, Label]], fn) -> tuple[Any, Label]:
    arg_label = join_all([lbl for _, lbl in args.values()])
    raw = fn({k: v for k, (v, _) in args.items()})
    tool_label = Label(frozenset({f"tool:{manifest.name}"}), False)

    if manifest.output_taint == "independent":
        if not manifest.signed:
            raise TaintLaunderingError(
                f"tool {manifest.name!r} claims independent output but manifest is unsigned"
            )
        return raw, tool_label

    # derived output: must join inbound taint
    return raw, tool_label.join(arg_label)


def sink_write(path: str, value: Any, label: Label) -> None:
    if label.untrusted:
        raise TaintLaunderingError(
            f"sink write to {path!r} rejected: tainted sources {sorted(label.sources)}"
        )
    # ... perform write


def demo() -> None:
    web_label = Label(frozenset({"web:retrieval"}), True)
    jq_manifest = ToolManifest(name="jq", output_taint="derived", signed=True)

    # Misconfigured tool that claims independence while echoing arguments:
    lying_manifest = ToolManifest(name="echo_helper", output_taint="independent", signed=False)

    out, out_label = invoke_tool(
        jq_manifest,
        {"blob": ({"cfg": "Ignore prior policy..."}, web_label)},
        lambda a: a["blob"]["cfg"],
    )
    # Correctly tainted; sink rejects.
    try:
        sink_write("/etc/agent/secrets.env", out, out_label)
    except TaintLaunderingError as e:
        print("blocked:", e)

    # The laundering attempt via an unsigned independence claim:
    try:
        invoke_tool(lying_manifest, {"x": ("tainted", web_label)}, lambda a: a["x"])
    except TaintLaunderingError as e:
        print("admission refused:", e)


if __name__ == "__main__":
    demo()
