# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-through-tool-output-re-ingestion.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-prompt-injection-taint-from-laundering-through-tool-output-re-ingestion.warrant.json
# Markdown SHA-256:   06680c43ff1119b0d3f708e7c75fcbeb302cdc049ce3f4b4d8fcfe63b957bc13
# Code AST SHA-256:   a0fd9aca2bb3525af81fe5425e5d1f309c8dcb34ac04a64204520e1bb74fc732
# Verified Classes:   Trust, TaintLaunderingError, Labeled
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Trust(IntEnum):
    """Trust ordering: higher = more trusted. Join is min() in this order."""
    UNTRUSTED = 0
    DERIVED = 1
    TRUSTED = 2


class TaintLaunderingError(RuntimeError):
    """Raised when a value is downgraded without an auditable declassifier,
    or when a join would escalate trust across a re-ingestion boundary."""


@dataclass
class Labeled:
    value: str
    label: Trust
    provenance: tuple[str, ...] = field(default_factory=tuple)


def join(*labels: Trust) -> Trust:
    """Least upper bound in the trust lattice == most restrictive wins.
    This is the single enforcement point that prevents re-ingestion loops
    from self-laundering."""
    if not labels:
        raise TaintLaunderingError("join() called with no labels")
    return Trust(min(int(l) for l in labels))


def model_transform(inputs: Iterable[Labeled], output: str) -> Labeled:
    """A model-mediated transformation is a join, never a copy.
    The output inherits the most restrictive label of any contributing input."""
    inputs = list(inputs)
    if not inputs:
        raise TaintLaunderingError("model_transform requires at least one labeled input")
    combined = join(*(i.label for i in inputs))
    provenance = tuple(p for i in inputs for p in i.provenance)
    return Labeled(value=output, label=combined, provenance=provenance)


def declassify(item: Labeled, *, declassifier: str, proof: str) -> Labeled:
    """The ONLY path that may raise a label's trust. Requires an auditable
    declassifier identity and a proof string (schema match, signature, approval id)."""
    if not declassifier or not proof:
        raise TaintLaunderingError(
            f"declassify of {item.provenance} attempted with no declassifier/proof"
        )
    return Labeled(value=item.value, label=Trust.TRUSTED,
                   provenance=item.provenance + (f"declassified:{declassifier}:{proof}",))


def write_scratchpad(store: dict[str, Labeled], key: str, item: Labeled) -> None:
    """Re-ingestion boundary: if the key already exists, the write is a JOIN,
    not an overwrite. This is what stops the 'retrieved N times, self-laundered'
    escalation."""
    if key in store:
        existing = store[key]
        merged_label = join(existing.label, item.label)
        if merged_label > existing.label:
            raise TaintLaunderingError(
                f"scratchpad write to {key!r} would escalate label "
                f"{existing.label.name} -> {merged_label.name}; "
                f"provenance={item.provenance}"
            )
        store[key] = Labeled(
            value=item.value,
            label=merged_label,
            provenance=existing.provenance + item.provenance,
        )
    else:
        store[key] = item


def privileged_sink(required: Trust, arg: Labeled) -> None:
    """Sink enforcement. Correct, but insufficient alone — the attack in the
    record passed this check because the label was laundered upstream."""
    if arg.label < required:
        raise TaintLaunderingError(
            f"sink requires {required.name}, got {arg.label.name}; "
            f"provenance={arg.provenance}"
        )


def demo_laundering_attempt() -> None:
    store: dict[str, Labeled] = {}
    chunk = Labeled(value="...assignee=<attacker>...", label=Trust.DERIVED,
                    provenance=("retrieve:doc#42",))
    summary = model_transform([chunk], "set assignee to attacker per source")
    # First write: label is DERIVED, allowed.
    write_scratchpad(store, "summary", summary)
    # Re-ingest the same chunk: join(DERIVED, DERIVED) is stable, no escalation.
    again = model_transform([chunk, store["summary"]], "set assignee to attacker per source")
    write_scratchpad(store, "summary", again)
    # A naive implementation that had labeled `summary` as TRUSTED here would
    # now pass the sink. With monotonic join it does not:
    try:
        privileged_sink(Trust.TRUSTED, store["summary"])
    except TaintLaunderingError as e:
        print(f"blocked as expected: {e}")
    # The only way through is an explicit declassifier:
    clean = declassify(store["summary"], declassifier="schema_validate",
                       proof="assignee matches ^[a-z0-9_-]{3,32}$")
    privileged_sink(Trust.TRUSTED, clean)


if __name__ == "__main__":
    demo_laundering_attempt()
