# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-across-a-tool-sandbox-when-retrieved-content-is-laundered-through-a-summarization-hop-before-reaching.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-enforce-taint-propagation-across-a-tool-sandbox-when-retrieved-content-is-laundered-through-a-summarization-hop-before-reaching.warrant.json
# Markdown SHA-256:   1f1e01cec9ce6546ee2f6c2b82b7dbc8fb956f02d22547e5c301975d38fb6f0b
# Code AST SHA-256:   4182a9d727064872a1c55739bc664818d8daf8d2bb41cee70ea4c1e531fef55f
# Verified Classes:   TaintLaunderingError, Node, ProvenanceGraph
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink has an undeclassified untrusted ancestor."""
    pass


@dataclass
class Node:
    id: str
    kind: str                      # "read" | "emit" | "write" | "declassify"
    trust: str                     # "untrusted" | "trusted" | "declassified"
    parents: list[str] = field(default_factory=list)


class ProvenanceGraph:
    def __init__(self) -> None:
        self.nodes: dict[str, Node] = {}

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

    def ancestry(self, node_id: str) -> set[str]:
        seen: set[str] = set()
        stack = [node_id]
        while stack:
            cur = stack.pop()
            if cur in seen:
                continue
            seen.add(cur)
            stack.extend(self.nodes[cur].parents)
        return seen

    def has_undeclassified_untrusted_path(self, sink_id: str) -> Optional[str]:
        """Return the offending untrusted node id, or None if clean."""
        sink = self.nodes[sink_id]
        for anc_id in self.ancestry(sink_id):
            anc = self.nodes[anc_id]
            if anc.trust != "untrusted":
                continue
            # Walk forward from anc to sink; if any path avoids a declassify node, it's a leak.
            if not self._every_path_declassified(anc_id, sink_id):
                return anc_id
        return None

    def _every_path_declassified(self, src: str, dst: str) -> bool:
        # DFS over forward edges; a path is safe only if it hits a declassify node.
        # Build forward adjacency lazily.
        fwd: dict[str, list[str]] = {n: [] for n in self.nodes}
        for nid, node in self.nodes.items():
            for p in node.parents:
                fwd[p].append(nid)

        # Find any path src->dst with zero declassify nodes.
        stack = [(src, False)]
        visited: set[tuple[str, bool]] = set()
        while stack:
            cur, saw_declass = stack.pop()
            if (cur, saw_declass) in visited:
                continue
            visited.add((cur, saw_declass))
            if cur == dst and not saw_declass:
                return False
            if self.nodes[cur].kind == "declassify":
                saw_declass = True
            for nxt in fwd[cur]:
                stack.append((nxt, saw_declass))
        return True


def enforce_privileged_call(graph: ProvenanceGraph, sink_id: str) -> None:
    offender = graph.has_undeclassified_untrusted_path(sink_id)
    if offender is not None:
        raise TaintLaunderingError(
            f"privileged sink {sink_id!r} has undeclassified untrusted ancestor "
            f"{offender!r}; block and require an explicit declassifier"
        )


# Demonstration of the laundering hop that value-identity tracking misses.
g = ProvenanceGraph()
g.add(Node("read:vendor_page", "read", "untrusted"))
g.add(Node("emit:summary_S1", "emit", "trusted", parents=["read:vendor_page"]))
g.add(Node("write:authorized_keys", "write", "trusted", parents=["emit:summary_S1"]))

# Value-identity tracker: body is "trusted", path is literal -> would allow.
# Provenance tracker: S1's ancestry includes the untrusted read, no declassify -> deny.
try:
    enforce_privileged_call(g, "write:authorized_keys")
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")

# With a schema-constrained declassifier on the path, the call is permitted.
g.add(Node("declass:path_schema", "declassify", "declassified",
           parents=["emit:summary_S1"]))
g.add(Node("write:authorized_keys_v2", "write", "trusted",
           parents=["declass:path_schema"]))
enforce_privileged_call(g, "write:authorized_keys_v2")  # passes
