# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-provenance-at-the-second-tool-boundary-not-the-first.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-lose-injection-taint-provenance-at-the-second-tool-boundary-not-the-first.warrant.json
# Markdown SHA-256:   4c1e0f53da06df4990be2e8a5315e00e86716c1fa00cf191adb47ba209342195
# Code AST SHA-256:   504644f2155f924d7acb6f6fe7587dc9301979d048f038c5615673db5648b941
# Verified Classes:   TaintLaunderingError, ProvenanceNode, ProvenanceGraph
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when tainted lineage reaches a sink without audited declassification."""
    pass


@dataclass
class ProvenanceNode:
    node_id: str
    tainted: bool
    source: Optional[str] = None
    declassified: bool = False
    parents: list = field(default_factory=list)


class ProvenanceGraph:
    def __init__(self) -> None:
        self.nodes: dict = {}

    def add(self, node: ProvenanceNode) -> None:
        self.nodes[node.node_id] = node

    def lineage_roots(self, node_id: str) -> list:
        seen, stack, roots = set(), [node_id], []
        while stack:
            nid = stack.pop()
            if nid in seen:
                continue
            seen.add(nid)
            node = self.nodes[nid]
            if not node.parents:
                roots.append(node)
            else:
                stack.extend(node.parents)
        return roots

    def is_tainted(self, node_id: str) -> bool:
        # Taint is monotonic along the DAG unless an audited declassifier sits on the path.
        for root in self.lineage_roots(node_id):
            if root.tainted and not root.declassified:
                return True
        return False


def enforce_sink(graph: ProvenanceGraph, arg_node_ids: list, sink_name: str) -> None:
    for nid in arg_node_ids:
        if graph.is_tainted(nid):
            raise TaintLaunderingError(
                f"sink '{sink_name}' received tainted lineage via node '{nid}' "
                f"with no audited declassification on the path"
            )


def demo() -> None:
    g = ProvenanceGraph()
    g.add(ProvenanceNode("fetch_page", tainted=True, source="web"))
    # Transformer inherits taint from its input argument; shape is irrelevant.
    g.add(ProvenanceNode("extract_field_out", tainted=False, parents=["fetch_page"]))
    # Sink closure check walks lineage back to the tainted root.
    enforce_sink(g, ["extract_field_out"], "send_message")


if __name__ == "__main__":
    demo()
