# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-a-taint-tagged-agent-from-laundering-untrusted-data-through-a-trusted-tool-s-return-channel.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-a-taint-tagged-agent-from-laundering-untrusted-data-through-a-trusted-tool-s-return-channel.warrant.json
# Markdown SHA-256:   261dfa0fa930ea1175479811291e2635967117bfe8b0cfbcaa2785940b8b0055
# Code AST SHA-256:   2212550c993cc347d388f7b5feafff81e5893c458ad3981918605960ff493a54
# Verified Classes:   TaintLaunderingError, Value
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a CLEAN-labeled value carries TAINTED provenance."""


@dataclass(frozen=True)
class Value:
    payload: object
    label: str                       # "CLEAN" | "TAINTED"
    origins: FrozenSet[str] = field(default_factory=frozenset)  # tainted origin ids


def join_label(a: str, b: str) -> str:
    return "TAINTED" if "TAINTED" in (a, b) else "CLEAN"


def invoke_declassifier(tool: str, arg: Value, output: object,
                        independence_proven: bool) -> Value:
    # Structural declassifiers (parse/extract/template) have no independence
    # proof for their output; they must inherit the argument's taint.
    if not independence_proven:
        out_label = join_label(arg.label, "TAINTED" if arg.label == "TAINTED" else "CLEAN")
        return Value(output, out_label, arg.origins)
    # Genuine declassifier: output bounded, provenance still recorded.
    return Value(output, "CLEAN", arg.origins)


def gate_sink(sink: str, arg: Value, authorized_origins: FrozenSet[str]) -> None:
    # Tripwire: CLEAN label with tainted provenance is a laundering signature.
    if arg.label == "CLEAN" and arg.origins:
        raise TaintLaunderingError(
            f"sink {sink!r} received CLEAN value with tainted provenance "
            f"{sorted(arg.origins)}; declassifier emitted an unsound label"
        )
    if arg.label == "TAINTED" and not (arg.origins <= authorized_origins):
        raise TaintLaunderingError(
            f"sink {sink!r} blocked: tainted origins {sorted(arg.origins)} "
            f"not in authorized set {sorted(authorized_origins)}"
        )


def run_pipeline(fetch_bytes: Value, authorized: FrozenSet[str]) -> None:
    # json.parse is structural: output is a subterm of input, no independence proof.
    parsed = invoke_declassifier("json.parse", fetch_bytes,
                                 {"summary": "..."}, independence_proven=False)
    # parsed.label == "TAINTED"; the following gate must block unless authorized.
    gate_sink("send_email", parsed, authorized)
