# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-provenance-label-laundering-across-tool-output-re-summarization-in-tainted-agent-loops.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-provenance-label-laundering-across-tool-output-re-summarization-in-tainted-agent-loops.warrant.json
# Markdown SHA-256:   e211b87984a4136a1b9f2c4024358fa9979cf6558a5e60c5085e007ef7e1a794
# Code AST SHA-256:   c68f63b8d90548d940d11396f43edda7d65550c29bd3eca571d28951c0a5fda9
# Verified Classes:   TaintWashError, Taint, Span
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintWashError(RuntimeError):
    """Raised when a derivation would lower taint below the join of its inputs."""


class Taint(IntEnum):
    # Higher value == more trusted. Join (max-taint) is min() on this scale.
    UNTRUSTED_RETRIEVED = 0
    UNTRUSTED_TOOL = 1
    TRUSTED_TOOL = 2
    TRUSTED_USER = 3
    TRUSTED_SYSTEM = 4


@dataclass(frozen=True)
class Span:
    span_id: str
    taint: Taint
    derived_from: tuple[str, ...] = field(default_factory=tuple)


def join_taint(inputs: Iterable[Span]) -> Taint:
    """Least upper bound in the taint lattice: the *least trusted* input wins.

    A tool output may never be more trusted than its most-untrusted input.
    """
    spans = list(inputs)
    if not spans:
        # Fail-closed: unknown provenance is treated as retrieved-untrusted.
        return Taint.UNTRUSTED_RETRIEVED
    return Taint(min(s.taint for s in spans))


def derive_output(
    tool_id: str,
    declared_inputs: Iterable[Span],
    emitter_declared_taint: Taint,
) -> Span:
    """Stamp a tool output with provenance derived from its actual inputs.

    The emitter's *registry* trust (emitter_declared_taint) is irrelevant to the
    output's information-flow taint; only the input join matters (invariant C2).
    """
    inputs = list(declared_inputs)
    joined = join_taint(inputs)
    if emitter_declared_taint > joined:
        raise TaintWashError(
            f"tool {tool_id!r} attempted to emit taint {emitter_declared_taint.name} "
            f"above input join {joined.name}; this is provenance laundering "
            f"(invariant C2 violated)"
        )
    return Span(
        span_id=f"{tool_id}:out",
        taint=joined,
        derived_from=tuple(s.span_id for s in inputs),
    )


MUTATING_TOOLS = frozenset({"write_file", "exec", "http_post", "credential_use"})


def authorize_call(
    tool_id: str,
    pending_inputs: Iterable[Span],
    ancestry: dict[str, Span],
) -> None:
    """Side-effect gate that reads the derivation join, not the message window (C3)."""
    inputs = list(pending_inputs)

    # C1: every input must have declared provenance; missing edges fail closed.
    for span in inputs:
        if span.span_id not in ancestry and span.taint > Taint.UNTRUSTED_RETRIEVED:
            raise TaintWashError(
                f"span {span.span_id!r} has undeclared ancestry; "
                f"failing closed per invariant C1"
            )

    joined = join_taint(inputs)

    # Walk the derivation DAG: a tainted ancestor anywhere blocks mutation.
    tainted_ancestor = joined <= Taint.UNTRUSTED_TOOL
    for span in inputs:
        for ancestor_id in span.derived_from:
            ancestor = ancestry.get(ancestor_id)
            if ancestor is not None and ancestor.taint <= Taint.UNTRUSTED_TOOL:
                tainted_ancestor = True
                break
        if tainted_ancestor:
            break

    if tool_id in MUTATING_TOOLS and tainted_ancestor:
        raise TaintWashError(
            f"blocked mutating call to {tool_id!r}: derivation join is {joined.name} "
            f"with untrusted ancestor; escalate to verifier (decision boundary)"
        )


# --- Reproduction of the observed failure and its fix ----------------------

def reproduce_laundering() -> None:
    page = Span("web_fetch:out", Taint.UNTRUSTED_RETRIEVED)
    ancestry = {page.span_id: page}

    # BUGGY path: labeler stamps by emitter registry identity.
    buggy = Span("summarize:out", Taint.TRUSTED_TOOL, derived_from=(page.span_id,))
    ancestry[buggy.span_id] = buggy
    # Gate sees only TRUSTED_TOOL in the window and permits the write.
    authorize_call("write_file", [buggy], ancestry)  # silently allowed -> wash

    # FIXED path: derive_output refuses to raise taint above the input join.
    try:
        derive_output("summarize", [page], emitter_declared_taint=Taint.TRUSTED_TOOL)
    except TaintWashError as exc:
        print(f"laundering caught: {exc}")

    # Correctly derived span carries the taint and blocks the mutation.
    fixed = derive_output("summarize", [page], emitter_declared_taint=Taint.UNTRUSTED_TOOL)
    ancestry[fixed.span_id] = fixed
    try:
        authorize_call("write_file", [fixed], ancestry)
    except TaintWashError as exc:
        print(f"mutation blocked: {exc}")


if __name__ == "__main__":
    reproduce_laundering()
