# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-write-after-tainted-tool-output-information-flow-label-laundering-through-summarization-and-re-retrieval.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-quarantine-a-memory-write-after-tainted-tool-output-information-flow-label-laundering-through-summarization-and-re-retrieval.warrant.json
# Markdown SHA-256:   14edd1d5d3f66b6635a8de8e80583602c2359b3748ea17c0187ac0d0be47f42c
# Code AST SHA-256:   84ce7cc126ef85abd0a0046455e6ba65c4975075f2ec79bacf4c7593a4297395
# Verified Classes:   Taint, TaintLaunderingError, ProvenanceNode, ProvenanceGraph
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, Set


class Taint(Enum):
    TRUSTED = 0
    UNTRUSTED = 1

    def join(self, other: "Taint") -> "Taint":
        return Taint(max(self.value, other.value))


class TaintLaunderingError(RuntimeError):
    """Raised when a memory write's provenance DAG is disconnected at an
    abstraction boundary (e.g. a summary node with no edge to its source),
    or when a tainted write targets an authority-bearing slot."""


AUTHORITY_BEARING_SLOTS: Set[str] = {
    "routing.api_base_url",
    "credentials.*",
    "tool.selection_policy",
    "system_prompt.fragment",
}


@dataclass
class ProvenanceNode:
    node_id: str
    taint: Taint
    parents: Set[str] = field(default_factory=set)


class ProvenanceGraph:
    def __init__(self) -> None:
        self._nodes: Dict[str, ProvenanceNode] = {}

    def register(self, node: ProvenanceNode) -> None:
        # A node claiming TRUSTED while having UNTRUSTED parents is a laundering
        # attempt at registration time; reject rather than silently accept.
        for parent_id in node.parents:
            if parent_id not in self._nodes:
                raise TaintLaunderingError(
                    f"node {node.node_id} references unregistered parent {parent_id}"
                )
            parent = self._nodes[parent_id]
            if node.taint.join(parent.taint) != node.taint:
                raise TaintLaunderingError(
                    f"node {node.node_id} labeled {node.taint.name} but parent "
                    f"{parent_id} is {parent.taint.name}: label laundering"
                )
        self._nodes[node.node_id] = node

    def reachable_taint(self, node_id: str) -> Taint:
        if node_id not in self._nodes:
            raise TaintLaunderingError(f"unknown provenance node {node_id}")
        seen: Set[str] = set()
        stack = [node_id]
        acc = Taint.TRUSTED
        while stack:
            current = stack.pop()
            if current in seen:
                continue
            seen.add(current)
            node = self._nodes[current]
            acc = acc.join(node.taint)
            stack.extend(node.parents)
        return acc

    def is_connected(self, node_id: str) -> bool:
        # A DERIVED summary must have parents; a parentless DERIVED node is a
        # severed edge at a compaction boundary.
        node = self._nodes[node_id]
        return node.taint == Taint.TRUSTED or bool(node.parents)


def gate_memory_write(
    graph: ProvenanceGraph,
    write_node_id: str,
    slot: str,
) -> str:
    """Returns 'accept', 'quarantine', or raises TaintLaunderingError."""
    if not graph.is_connected(write_node_id):
        raise TaintLaunderingError(
            f"write {write_node_id} has severed provenance edge "
            f"(DERIVED node with no parent): compaction laundering"
        )

    effective = graph.reachable_taint(write_node_id)

    is_authority = any(
        slot == a or (a.endswith(".*") and slot.startswith(a[:-1]))
        for a in AUTHORITY_BEARING_SLOTS
    )

    if effective == Taint.UNTRUSTED:
        if is_authority:
            raise TaintLaunderingError(
                f"tainted write {write_node_id} targets authority-bearing slot "
                f"{slot!r}: reject and flag source"
            )
        return "quarantine"

    return "accept"


# --- reproduction of the observed trace -------------------------------

if __name__ == "__main__":
    g = ProvenanceGraph()
    g.register(ProvenanceNode("fetch.attacker_page", Taint.UNTRUSTED))
    # compaction emits a summary node with a preserved edge (correct runtime)
    g.register(
        ProvenanceNode(
            "summary.1", Taint.UNTRUSTED, parents={"fetch.attacker_page"}
        )
    )
    g.register(ProvenanceNode("docs.search.clean", Taint.TRUSTED))

    # The poisoned consolidation write is drawn from summary.1 and the clean doc.
    g.register(
        ProvenanceNode(
            "write.deployment_config",
            Taint.UNTRUSTED,
            parents={"summary.1", "docs.search.clean"},
        )
    )

    try:
        gate_memory_write(g, "write.deployment_config", "routing.api_base_url")
    except TaintLaunderingError as exc:
        print(f"BLOCKED: {exc}")

    # Now the broken runtime: compaction drops the edge.
    g2 = ProvenanceGraph()
    g2.register(ProvenanceNode("fetch.attacker_page", Taint.UNTRUSTED))
    g2.register(ProvenanceNode("summary.1", Taint.TRUSTED))  # severed edge
    g2.register(ProvenanceNode("docs.search.clean", Taint.TRUSTED))
    g2.register(
        ProvenanceNode(
            "write.deployment_config",
            Taint.TRUSTED,
            parents={"summary.1", "docs.search.clean"},
        )
    )
    try:
        gate_memory_write(g2, "write.deployment_config", "routing.api_base_url")
    except TaintLaunderingError as exc:
        print(f"BLOCKED (severed edge): {exc}")
