# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-launder-tainted-data-through-a-re-entrant-tool-call-after-a-policy-check-passes.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-launder-tainted-data-through-a-re-entrant-tool-call-after-a-policy-check-passes.warrant.json
# Markdown SHA-256:   25ca777e2f3bffc39544c5a5b2f91ce26ed9ca6d052598102e2872b36b0c04e8
# Code AST SHA-256:   fd5ea3c8b15c401f1b0ed5003025de2fa806bdfe7eb85de30a6082420d498f7c
# Verified Classes:   TaintLabel, EgressClass, TaintLaunderingError, ToolSpec, Call, Turn
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintLabel(Enum):
    TRUSTED = "trusted"
    UNTRUSTED_DERIVED = "untrusted_derived"
    UNTRUSTED = "untrusted"


class EgressClass(Enum):
    NET_READ = "net_read"
    NET_WRITE = "net_write"


class TaintLaunderingError(RuntimeError):
    """Raised when a per-call-legal tool sequence composes into an illegal egress path."""


@dataclass(frozen=True)
class ToolSpec:
    name: str
    egress: EgressClass
    accepts: frozenset[TaintLabel]
    emits: TaintLabel
    certified_declassifier: bool = False


@dataclass
class Call:
    tool: str
    arg_label: TaintLabel
    source_call: int | None = None  # index into the turn's call list


@dataclass
class Turn:
    calls: list[Call] = field(default_factory=list)

    def append(self, tool: str, arg_label: TaintLabel, source_call: int | None) -> int:
        self.calls.append(Call(tool, arg_label, source_call))
        return len(self.calls) - 1


SINKS_ACCEPT = frozenset({TaintLabel.TRUSTED})

TOOLS: dict[str, ToolSpec] = {
    "fetch_url": ToolSpec("fetch_url", EgressClass.NET_READ,
                          frozenset({TaintLabel.TRUSTED}), TaintLabel.UNTRUSTED),
    # NOT certified: LLM-backed summarizer cannot bound input-controlled output.
    "summarize": ToolSpec("summarize", EgressClass.NET_READ,
                          frozenset({TaintLabel.UNTRUSTED, TaintLabel.UNTRUSTED_DERIVED}),
                          TaintLabel.UNTRUSTED_DERIVED, certified_declassifier=False),
    "post_webhook": ToolSpec("post_webhook", EgressClass.NET_WRITE,
                             SINKS_ACCEPT, TaintLabel.TRUSTED),
}


def check_call(tool: str, arg_label: TaintLabel) -> None:
    """Per-call gate. Correct, but insufficient alone."""
    spec = TOOLS[tool]
    if arg_label not in spec.accepts:
        raise TaintLaunderingError(
            f"per-call gate: {tool} rejects arg label {arg_label.value}"
        )


def check_turn_path(turn: Turn) -> None:
    """Path gate: reject if any UNTRUSTED source reaches a NET_WRITE sink
    through a transform that is not a certified declassifier."""
    for idx, call in enumerate(turn.calls):
        spec = TOOLS[call.tool]
        if spec.egress is not EgressClass.NET_WRITE:
            continue
        # Walk back the provenance chain.
        cursor = call.source_call
        while cursor is not None:
            upstream = turn.calls[cursor]
            up_spec = TOOLS[upstream.tool]
            if upstream.arg_label is TaintLabel.UNTRUSTED and not up_spec.certified_declassifier:
                raise TaintLaunderingError(
                    f"path gate: UNTRUSTED source at call {cursor} ({upstream.tool}) "
                    f"reaches NET_WRITE sink {idx} ({call.tool}) via "
                    f"non-certified transform"
                )
            cursor = upstream.source_call


def run_laundering_attempt() -> None:
    turn = Turn()
    # Step 1: fetch untrusted document.
    i0 = turn.append("fetch_url", TaintLabel.TRUSTED, source_call=None)
    check_call("fetch_url", TaintLabel.TRUSTED)
    # Step 2: summarize (LLM-backed, not a certified declassifier).
    i1 = turn.append("summarize", TaintLabel.UNTRUSTED, source_call=i0)
    check_call("summarize", TaintLabel.UNTRUSTED)  # passes: summarize accepts untrusted
    # Step 3: post the "clean" summary.
    emitted = TOOLS["summarize"].emits
    i2 = turn.append("post_webhook", emitted, source_call=i1)
    check_call("post_webhook", emitted)  # FAILS: emitted is UNTRUSTED_DERIVED, not TRUSTED
    # If a future runtime widens the sink to accept UNTRUSTED_DERIVED, the path
    # gate must still catch the composition:
    check_turn_path(turn)


if __name__ == "__main__":
    try:
        run_laundering_attempt()
    except TaintLaunderingError as exc:
        print(f"BLOCKED: {exc}")
