# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-propagate-information-flow-taint-labels-across-tool-call-boundaries-to-prevent-prompt-injection-laundering.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-propagate-information-flow-taint-labels-across-tool-call-boundaries-to-prevent-prompt-injection-laundering.warrant.json
# Markdown SHA-256:   96c09e4e950b2ba4ce149a9975658ddbe7e8400cd47718e9c5f9bb14f2b26d48
# Code AST SHA-256:   da62f84ad1ecf9953ce7e5947db3b4da3db48e67c5460f4aa1538696153c7442
# Verified Classes:   TaintViolation, Label, Tainted, ToolSpec, TaintRuntime
# Defensive Guards:   5 fail-closed invariants (zero external deps)

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


class TaintViolation(RuntimeError):
    """Raised when an UNTRUSTED value reaches a privileged sink without declassification."""


class Label(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1


def join(*labels: Label) -> Label:
    return Label(max(labels)) if labels else Label.TRUSTED


@dataclass
class Tainted:
    value: str
    label: Label


@dataclass
class ToolSpec:
    name: str
    # label_fn maps input labels to the output label. Default: conservative join.
    label_fn: Callable[[list[Label]], Label] = lambda ins: join(*ins)
    # A declassifier must justify downgrade via channel closure (typed output).
    declassifies: bool = False


class TaintRuntime:
    def __init__(self):
        self.specs: dict[str, ToolSpec] = {}
        self.audit: list[tuple[str, Label, Label]] = []

    def register(self, spec: ToolSpec) -> None:
        self.specs[spec.name] = spec

    def invoke(self, name: str, args: list[Tainted]) -> Tainted:
        spec = self.specs[name]
        in_labels = [a.label for a in args]
        out_label = spec.label_fn(in_labels)
        if spec.declassifies and out_label == Label.UNTRUSTED:
            # Declassification must be explicit and audited; here we refuse silent downgrade.
            raise TaintViolation(
                f"tool {name!r} declared declassifier but produced UNTRUSTED from "
                f"{in_labels}; channel not closed"
            )
        # Simulate tool output; in reality this is the tool's return value.
        out_value = f"<{name} output derived from {len(args)} inputs>"
        result = Tainted(out_value, out_label)
        self.audit.append((name, join(*in_labels), out_label))
        return result

    def sink(self, name: str, args: list[Tainted], approval: bool = False) -> None:
        worst = join(*[a.label for a in args])
        if worst == Label.UNTRUSTED and not approval:
            raise TaintViolation(
                f"privileged sink {name!r} received UNTRUSTED argument; "
                f"blocked pending human approval"
            )


def demo() -> None:
    rt = TaintRuntime()
    rt.register(ToolSpec("fetch_url", label_fn=lambda ins: Label.UNTRUSTED))
    # summarize transforms bytes and can carry imperatives -> must join, NOT declassify
    rt.register(ToolSpec("summarize"))
    rt.register(ToolSpec("send_email"))

    page = rt.invoke("fetch_url", [])
    assert page.label == Label.UNTRUSTED

    summary = rt.invoke("summarize", [page])
    # The critical invariant: transformation does not launder taint.
    if summary.label != Label.UNTRUSTED:
        raise TaintViolation("taint laundered across summarize boundary")

    # Attempting to drive a privileged sink with the derived value is blocked.
    try:
        rt.sink("send_email", [summary])
    except TaintViolation:
        return
    raise TaintViolation("sink accepted tainted derived value")


if __name__ == "__main__":
    demo()
