# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-result-as-taint-propagating-rather-than-as-an-ordinary-observation-dynamic-information-flow-labels-and.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-tool-result-as-taint-propagating-rather-than-as-an-ordinary-observation-dynamic-information-flow-labels-and.warrant.json
# Markdown SHA-256:   30f4fe238d7e0b2882c158f0ebd9ed0c8d119bf9db20bf70533432b4bee6a614
# Code AST SHA-256:   446d99d84da0295cb27aaf02aec77ec0ceba769dbf52c858352f78f3b47e609a
# Verified Classes:   TaintLaunderingError, Label, ToolSpec, ProvenanceLabeler
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Dict, List, Set


class TaintLaunderingError(RuntimeError):
    """Raised when a tool output would be assigned a label weaker than the join of its inputs
    without an explicit, reviewed declassification."""


@dataclass(frozen=True)
class Label:
    untrusted_sources: frozenset = frozenset()

    def join(self, other: "Label") -> "Label":
        return Label(self.untrusted_sources | other.untrusted_sources)

    @property
    def is_tainted(self) -> bool:
        return bool(self.untrusted_sources)


@dataclass
class ToolSpec:
    name: str
    base_label: Label
    is_declassifier: bool = False
    declassify_reason: str = ""


class ProvenanceLabeler:
    def __init__(self, registry: Dict[str, ToolSpec]):
        self.registry = registry
        # provenance graph: output_id -> (tool_name, tuple(input_ids))
        self.provenance: Dict[str, tuple] = {}

    def label_tool_output(
        self,
        tool_name: str,
        input_labels: List[Label],
        output_id: str,
    ) -> Label:
        spec = self.registry.get(tool_name)
        if spec is None:
            raise TaintLaunderingError(
                f"tool {tool_name!r} not registered; refusing to assign a label"
            )

        joined_inputs = Label()
        for lbl in input_labels:
            joined_inputs = joined_inputs.join(lbl)

        computed = spec.base_label.join(joined_inputs)

        if spec.is_declassifier:
            if not spec.declassify_reason:
                raise TaintLaunderingError(
                    f"declassifier {tool_name!r} has no declassify_reason; "
                    "declassification must be reviewed and justified"
                )
            assigned = spec.base_label
        else:
            assigned = computed

        # Invariant: assigned must be at least as tainted as computed, unless declassifier.
        if not spec.is_declassifier and assigned.is_tainted != computed.is_tainted:
            raise TaintLaunderingError(
                f"label laundering at tool {tool_name!r}: "
                f"inputs tainted={computed.is_tainted}, assigned tainted={assigned.is_tainted}"
            )

        self.provenance[output_id] = (tool_name, tuple(input_labels))
        return assigned

    def trace_laundering(self, output_id: str) -> List[str]:
        """Reconstruct the provenance chain for forensic review."""
        chain: List[str] = []
        stack = [output_id]
        seen: Set[str] = set()
        while stack:
            oid = stack.pop()
            if oid in seen:
                continue
            seen.add(oid)
            entry = self.provenance.get(oid)
            if entry is None:
                chain.append(f"{oid}: <root>")
                continue
            tool, inputs = entry
            chain.append(f"{oid}: via {tool}")
            for lbl in inputs:
                if lbl.is_tainted:
                    chain.append(f"  <- tainted from {sorted(lbl.untrusted_sources)}")
        return chain


def demo():
    registry = {
        "fetch": ToolSpec("fetch", Label(frozenset({"web"}))),
        "summarize": ToolSpec("summarize", Label(frozenset())),  # trusted impl, but NOT a declassifier
        "noop": ToolSpec("noop", Label(frozenset())),
    }
    labeler = ProvenanceLabeler(registry)

    doc_label = labeler.label_tool_output("fetch", [], "doc-1")
    # doc_label is tainted
    summary_label = labeler.label_tool_output("summarize", [doc_label], "sum-1")
    assert summary_label.is_tainted, "summarize must propagate taint"

    # A misconfigured registry that marks summarize as a declassifier with no reason:
    bad_registry = dict(registry)
    bad_registry["summarize"] = ToolSpec("summarize", Label(frozenset()), is_declassifier=True)
    bad_labeler = ProvenanceLabeler(bad_registry)
    try:
        bad_labeler.label_tool_output("summarize", [doc_label], "sum-bad")
    except TaintLaunderingError as e:
        print(f"blocked: {e}")

    print("provenance:", labeler.trace_laundering("sum-1"))


if __name__ == "__main__":
    demo()
