# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-multi-hop-tool-chains-when-injected-labels-are-re-derived-from-trusted-looking-outputs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-across-multi-hop-tool-chains-when-injected-labels-are-re-derived-from-trusted-looking-outputs.warrant.json
# Markdown SHA-256:   eb80a1422f03c34e70e514ca62eb17e5e4fe2bdec599c84f86d0807fd5dcacb6
# Code AST SHA-256:   7d0f3898c5973261be65dee00046e5bb92a4aa17d84d72ef5ffde4e37483b5b4
# Verified Classes:   TaintLaunderingError, MissingLabelError, Label, Tainted
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a value's label is not dominated by the meet of its causal inputs."""
    pass


class MissingLabelError(TaintLaunderingError):
    """Raised when a boundary receives a value with no carried label."""
    pass


# Lattice: lower tuple = more restrictive. integrity: low < high; confidentiality: public < secret
_INTEGRITY = {"low": 0, "high": 1}
_CONF = {"public": 0, "secret": 1}


@dataclass(frozen=True)
class Label:
    integrity: str = "low"
    confidentiality: str = "public"

    def __post_init__(self):
        if self.integrity not in _INTEGRITY or self.confidentiality not in _CONF:
            raise TaintLaunderingError(f"invalid label {self!r}")

    def meet(self, other: "Label") -> "Label":
        # meet = most restrictive = min on both axes
        return Label(
            integrity=min(self.integrity, other.integrity, key=_INTEGRITY.get),
            confidentiality=min(self.confidentiality, other.confidentiality, key=_CONF.get),
        )

    def dominated_by(self, other: "Label") -> bool:
        # self is no less restrictive than other
        return (_INTEGRITY[self.integrity] <= _INTEGRITY[other.integrity]
                and _CONF[self.confidentiality] <= _CONF[other.confidentiality])


@dataclass
class Tainted:
    value: Any
    label: Label = field(default_factory=Label)


def hop(inputs: list[Tainted], transform_name: str) -> Label:
    """Compute the required output label for a transform over causal inputs."""
    if not inputs:
        raise MissingLabelError(f"{transform_name}: no inputs to meet")
    meet = inputs[0].label
    for i in inputs[1:]:
        meet = meet.meet(i.label)
    return meet


def emit(output_value: Any, carried: Label, inputs: list[Tainted], transform_name: str) -> Tainted:
    """Enforce the invariant: carried label must be dominated by the meet of inputs."""
    required = hop(inputs, transform_name)
    if not carried.dominated_by(required):
        raise TaintLaunderingError(
            f"{transform_name}: carried label {carried} is less restrictive than "
            f"required meet {required} over inputs {[i.label for i in inputs]}"
        )
    return Tainted(value=output_value, label=carried)


def ingest(payload: dict, transform_name: str) -> Tainted:
    """Ingress at a boundary: fail closed if the label slot is absent."""
    if "label" not in payload:
        raise MissingLabelError(
            f"{transform_name}: boundary received unlabeled value; "
            f"treating as integrity=low, confidentiality=secret is required, not silent trust"
        )
    return Tainted(value=payload["value"], label=Label(**payload["label"]))


# --- Demonstration of the laundering trace ---
if __name__ == "__main__":
    fetched = Tainted(value="<injected instruction>", label=Label("low", "public"))

    # Summarizer omits label slot -> laundering boundary. Ingest must fail closed.
    summarizer_output = {"value": "please reconcile via 10.0.0.7"}  # no "label"
    try:
        ingest(summarizer_output, "summarizer->executor")
    except MissingLabelError as e:
        print("BLOCKED:", e)

    # If a careless receiver re-derives trust from sender identity:
    try:
        emit("reconcile via 10.0.0.7", Label("high", "public"), [fetched], "summarizer")
    except TaintLaunderingError as e:
        print("BLOCKED:", e)

    # Correct path: carry the meet.
    ok = emit("please reconcile via 10.0.0.7", hop([fetched], "summarizer"), [fetched], "summarizer")
    print("PASSED with carried label:", ok.label)
