# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-label-laundering-when-a-tainted-value-is-re-serialized-through-a-trusted-tool-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-label-laundering-when-a-tainted-value-is-re-serialized-through-a-trusted-tool-boundary.warrant.json
# Markdown SHA-256:   aee4398ab6e8d94a9e83f5f8fd2ddeea21e81cbed7f3a7201581384efecc70ac
# Code AST SHA-256:   2a86c473e2b716f083fcfda96250f77727c75c16f3b302e76a688816f8ce005d
# Verified Classes:   LabelLaunderingError, Labeled
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable

# Label lattice: TRUSTED < DERIVED < UNTRUSTED < TOP
_RANK = {"TRUSTED": 0, "DERIVED": 1, "UNTRUSTED": 2, "TOP": 3}
_BLOCK_THRESHOLD = _RANK["UNTRUSTED"]


class LabelLaunderingError(RuntimeError):
    """Raised when a tool boundary would lower a propagated taint label."""


@dataclass(frozen=True)
class Labeled:
    value: str
    label: str
    provenance: tuple = field(default_factory=tuple)

    def join(self, other: "Labeled") -> "Labeled":
        hi = self.label if _RANK[self.label] >= _RANK[other.label] else other.label
        return Labeled(self.value, hi, self.provenance + other.provenance)


def join_labels(inputs: Iterable[Labeled], declared_floor: str) -> str:
    """Compute output label as floor ⊔ (join of all input labels). Never substitutes."""
    floor_rank = _RANK[declared_floor]
    for inp in inputs:
        if _RANK[inp.label] > floor_rank:
            floor_rank = _RANK[inp.label]
    return next(k for k, v in _RANK.items() if v == floor_rank)


def register_tool(name: str, declared_output_trust: str, reachable_input_labels: Iterable[str]) -> None:
    """Reject tools whose declared output trust would launder a reachable input label."""
    floor = _RANK[declared_output_trust]
    for lbl in reachable_input_labels:
        if _RANK.get(lbl, _RANK["TOP"]) > floor:
            raise LabelLaunderingError(
                f"tool {name!r} declares output={declared_output_trust!r} "
                f"but reachable input label {lbl!r} exceeds it; "
                f"boundary would discard provenance (laundering vector)"
            )


def apply_boundary(tool: str, declared_floor: str, inputs: list[Labeled]) -> Labeled:
    """Re-serialize through a tool boundary, preserving the joined label."""
    out_label = join_labels(inputs, declared_floor)
    for inp in inputs:
        if _RANK[inp.label] > _RANK[out_label]:
            raise LabelLaunderingError(
                f"boundary {tool!r} produced label {out_label!r} "
                f"below input label {inp.label!r}"
            )
    merged = inputs[0]
    for inp in inputs[1:]:
        merged = merged.join(inp)
    return Labeled(merged.value, out_label, merged.provenance + ((tool, out_label),))


def sink_check(tool: str, arg: Labeled) -> None:
    """Fail-closed: unknown labels are TOP and block."""
    rank = _RANK.get(arg.label, _RANK["TOP"])
    if rank >= _BLOCK_THRESHOLD:
        raise LabelLaunderingError(
            f"sink {tool!r} blocked: arg label {arg.label!r} "
            f"(provenance={arg.provenance}) at/above threshold"
        )


# --- reproduction of the laundering trace ---
def reproduce() -> None:
    fetch = Labeled("…; rm -rf ~/tmp ;…", "UNTRUSTED", ("web_fetch",))
    # Correct boundary: join preserves UNTRUSTED.
    out = apply_boundary("extract_field", "DERIVED", [fetch])
    if out.label != "UNTRUSTED":
        raise LabelLaunderingError(f"expected UNTRUSTED, got {out.label!r}")
    # Sink must block.
    try:
        sink_check("run_command", out)
    except LabelLaunderingError:
        return
    raise LabelLaunderingError("sink failed to block laundered-but-tainted arg")


# --- registration-time guard against the defective tool contract ---
def register_defective_tool() -> None:
    # Declares output=DERIVED but a reachable input is UNTRUSTED -> must raise.
    register_tool("extract_field", "DERIVED", ["TRUSTED", "UNTRUSTED"])
    raise LabelLaunderingError("defective tool contract was accepted; join invariant not enforced")


if __name__ == "__main__":
    reproduce()
    try:
        register_defective_tool()
    except LabelLaunderingError as e:
        print("registration rejected:", e)
