# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-tainted-tool-call-the-label-erasure-boundary-in-mcp-hosted-sandbox-servers.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-tainted-tool-call-the-label-erasure-boundary-in-mcp-hosted-sandbox-servers.warrant.json
# Markdown SHA-256:   7ef2152d9a41d27b83f8ec8eb2b57c82be886f4eefb53af251ad1bc1d8fb3410
# Code AST SHA-256:   696ab4570772c4b7a20cb6cad8bcc8fb388561c01a030b73a366b86f919e312a
# Verified Classes:   Label, TaintEscalationError, Provenance, SinkPolicy
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class Label(IntEnum):
    PUBLIC = 0
    INTERNAL = 1
    SECRET = 2


def join(labels: Iterable[Label]) -> Label:
    return max(labels, default=Label.SECRET)  # default-to-tainted, not PUBLIC


class TaintEscalationError(RuntimeError):
    """Raised when a privileged sink would receive a value whose provenance
    cannot be reconstructed to a clean source."""


@dataclass
class Provenance:
    """Tracks which labels have flowed into a value produced by the agent."""

    sources: set[Label] = field(default_factory=set)

    def derived_from(self, other: "Provenance") -> "Provenance":
        # Any transform the sandbox does not model must preserve labels.
        return Provenance(self.sources | other.sources)

    @property
    def effective(self) -> Label:
        return join(self.sources)


@dataclass
class SinkPolicy:
    name: str
    external: bool
    max_label: Label


MAIL_SEND = SinkPolicy(name="mail.send", external=True, max_label=Label.PUBLIC)


def check_sink(policy: SinkPolicy, arg_provenance: Provenance, declassified: bool) -> None:
    eff = arg_provenance.effective
    if declassified:
        return
    if policy.external and eff > policy.max_label:
        raise TaintEscalationError(
            f"sink {policy.name!r} is external but argument provenance "
            f"joins to {eff.name}; refusing confused-deputy escalation. "
            f"Require explicit declassify(value, to=PUBLIC) before send."
        )


def run_agent_step(context_provenance: Provenance, policy: SinkPolicy, body_provenance: Provenance) -> None:
    # The agent's context already holds whatever it has read this turn.
    combined = body_provenance.derived_from(context_provenance)
    check_sink(policy, combined, declassified=False)


if __name__ == "__main__":
    ctx = Provenance({Label.SECRET})          # notes.read returned secret data
    body = Provenance()                        # model emitted a plain string: no label
    try:
        run_agent_step(ctx, MAIL_SEND, body)   # would have passed under default-to-public
    except TaintEscalationError as e:
        print("BLOCKED:", e)
