# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundered-privilege-escalation-across-a-multi-tool-agent-sandbox.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundered-privilege-escalation-across-a-multi-tool-agent-sandbox.warrant.json
# Markdown SHA-256:   463f5b4838233e1a424acea0c3a1252cafd63360ad9a117e87478e417abe222b
# Code AST SHA-256:   c27731119613bdbc30ac59b9fd87bfed0996901b9f126d170907cb730c98c100
# Verified Classes:   Taint, Derivation, TaintLaunderingError, TaskState
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import Enum
from typing import FrozenSet


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


def join(a: Taint, b: Taint) -> Taint:
    return Taint(max(a.value, b.value))


@dataclass(frozen=True)
class Derivation:
    """Derivation closure for a single tool argument."""
    leaves: FrozenSet[str] = field(default_factory=frozenset)
    label: Taint = Taint.TRUSTED

    def model_transform(self) -> "Derivation":
        # Model-mediated transformation is a JOIN, never a reset.
        # The output inherits the full leaf set and joined label of its inputs.
        return Derivation(leaves=self.leaves, label=self.label)


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged tool argument's derivation closure is not TRUSTED."""


@dataclass
class TaskState:
    """Derivation closure accumulated across the whole task."""
    leaves: FrozenSet[str] = field(default_factory=frozenset)
    label: Taint = Taint.TRUSTED

    def absorb(self, d: Derivation) -> None:
        self.leaves = self.leaves | d.leaves
        self.label = join(self.label, d.label)


PRIVILEGED_TOOLS = {"provision_scope", "exec_shell", "send_email"}


def authorize_tool_call(
    state: TaskState,
    tool: str,
    args: dict[str, Derivation],
    declassified: dict[str, bool] | None = None,
) -> None:
    if tool not in PRIVILEGED_TOOLS:
        return
    declassified = declassified or {}
    for name, deriv in args.items():
        # Model-emitted literals inherit the task's accumulated taint.
        effective = join(deriv.label, state.label) if deriv.leaves == frozenset() else deriv.label
        if effective is Taint.UNTRUSTED and not declassified.get(name, False):
            raise TaintLaunderingError(
                f"privileged tool {tool!r} arg {name!r} has UNTRUSTED derivation "
                f"closure {sorted(state.leaves | deriv.leaves)}; "
                f"declassify with a sandbox-side, value-exact check before retry"
            )


# --- Trace of the observed failure, now blocked ---
state = TaskState()
state.absorb(Derivation(leaves=frozenset({"fetch_url:vendor.example/onboard"}),
                        label=Taint.UNTRUSTED))

# Model paraphrased "admin:tenant:*" out of prose; it presents as a bare literal.
laundered_arg = Derivation(leaves=frozenset(), label=Taint.TRUSTED)

try:
    authorize_tool_call(state, "provision_scope", {"scope_id": laundered_arg})
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")
