# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-tool-call-return-channels-during-prompt-injection-propagation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-tool-call-return-channels-during-prompt-injection-propagation.warrant.json
# Markdown SHA-256:   183d3a6f491a321ee5b1ea93b5f71afab10d93d1cd7ae17e17a868c54b08b113
# Code AST SHA-256:   40548e7179d8b134db5f9483b9e43b9e85e1e090f73bc6fa5eb9d6c7b06db94c
# Verified Classes:   TaintLaunderingError, Label
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Mapping


class TaintLaunderingError(RuntimeError):
    """Raised when a trusted tool return is stamped above the join of its inputs."""


@dataclass(frozen=True)
class Label:
    trust: str  # "trusted" | "untrusted"
    sources: frozenset[str] = field(default_factory=frozenset)

    def join(self, other: "Label") -> "Label":
        # Taint is join-monotonic: untrusted absorbs trusted.
        trust = "untrusted" if "untrusted" in (self.trust, other.trust) else "trusted"
        return Label(trust, self.sources | other.sources)


def stamp_return(
    manifest_trust: str,
    arg_labels: Mapping[str, Label],
    dependency_map: Mapping[str, tuple[str, ...]] | None,
    output_field: str,
) -> Label:
    """Compute the label for one output field of a tool return.

    Invariant: label(out) = manifest_trust ⊓ join(labels of declared deps).
    If the dependency map is missing or does not cover the field, fall back
    to arg-join over ALL arguments (fail toward over-taint, never to trust).
    """
    if dependency_map is not None and output_field in dependency_map:
        deps = dependency_map[output_field]
        relevant = [arg_labels[a] for a in deps if a in arg_labels]
        if len(relevant) != len(deps):
            # Declared dependency references an argument we did not label.
            raise TaintLaunderingError(
                f"dependency map for {output_field!r} references unlabeled args {deps}"
            )
        joined = Label("trusted")
        for lab in relevant:
            joined = joined.join(lab)
    else:
        # Fail-closed: no verified dependency map -> join over every argument.
        joined = Label("trusted")
        for lab in arg_labels.values():
            joined = joined.join(lab)

    if manifest_trust == "trusted" and joined.trust == "untrusted":
        # The tool's code is trusted, but its output is derived from taint.
        return Label("untrusted", joined.sources)
    return Label(manifest_trust, joined.sources)


def gate_sink(
    sink_name: str,
    value: Any,
    value_label: Label,
    provenance_graph: Mapping[str, Label],
) -> None:
    """Sink gate must re-derive from the provenance graph, not read the stamp."""
    if value_label.trust == "trusted":
        return
    # Re-derivation: walk the graph edges that produced this value.
    derived = value_label
    for node_id, node_label in provenance_graph.items():
        if value_label.sources & node_label.sources:
            derived = derived.join(node_label)
    if derived.trust != "trusted":
        raise TaintLaunderingError(
            f"sink {sink_name!r} rejected: value derived from untrusted sources "
            f"{sorted(derived.sources)}; explicit declassification required"
        )
