# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-dynamic-information-flow-taint-labels-across-tool-boundaries-and-when-does-the-label-silently-detach.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-dynamic-information-flow-taint-labels-across-tool-boundaries-and-when-does-the-label-silently-detach.warrant.json
# Markdown SHA-256:   9584e068e7f68ce247ec11e9a6bd3446640b6066850ddd9b9246cc541744af64
# Code AST SHA-256:   ac46dba962b58509dd2ed5a95e006552524897bcd65eaf7f4579dcb4ff793df5
# Verified Classes:   Trust, PrivilegedSink, TaintBoundaryViolation, DerivationNode, ToolCall
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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


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


class PrivilegedSink:
    SEND_EMAIL = "send_email"
    READ_CREDENTIAL = "read_credential"
    WRITE_OUTSIDE_SANDBOX = "write_outside_sandbox"


class TaintBoundaryViolation(RuntimeError):
    """Raised when a privileged sink is reached from a tainted derivation path
    without a signed declassification record. This is the distillation-laundering
    guard: it checks the join of provenance across the whole path, not the
    label of the immediate argument string."""


@dataclass
class DerivationNode:
    node_id: str
    provenance: set[Trust]
    declassified_by: str | None = None  # signed declassification record id


@dataclass
class ToolCall:
    sink: str
    argument: str
    derivation_path: list[DerivationNode] = field(default_factory=list)


PRIVILEGED = {
    PrivilegedSink.SEND_EMAIL,
    PrivilegedSink.READ_CREDENTIAL,
    PrivilegedSink.WRITE_OUTSIDE_SANDBOX,
}


def join_provenance(path: Iterable[DerivationNode]) -> set[Trust]:
    joined: set[Trust] = set()
    for node in path:
        joined |= node.provenance
    return joined


def enforce_taint_boundary(call: ToolCall) -> None:
    if call.sink not in PRIVILEGED:
        return
    joined = join_provenance(call.derivation_path)
    if Trust.UNTRUSTED not in joined:
        return
    # A declassification record on the *final* derivation node is the only
    # sanctioned way to clear taint; an unlabeled argument with a tainted
    # path is exactly the distillation-laundering case and must be rejected.
    terminal = call.derivation_path[-1] if call.derivation_path else None
    if terminal is not None and terminal.declassified_by:
        return
    raise TaintBoundaryViolation(
        f"privileged sink {call.sink!r} reached from tainted derivation path "
        f"(nodes={[n.node_id for n in call.derivation_path]}, "
        f"joined_provenance={joined}); "
        f"argument={call.argument!r} carries no declassification record"
    )


# --- reproduction of the observed failure ---
raw_page = DerivationNode("fetch:page", {Trust.UNTRUSTED})
summary = DerivationNode("summarize:page", {Trust.UNTRUSTED})  # unmodeled transform
planner = DerivationNode("planner:reason", {Trust.TRUSTED})    # model's own text

# Boundary A (permissive, unsound here): checks only the terminal argument label.
# It sees planner.provenance == {TRUSTED} and permits the call.
# Boundary B (this guard): joins the whole path, sees UNTRUSTED, rejects.
call = ToolCall(
    sink=PrivilegedSink.SEND_EMAIL,
    argument="audit@attacker.example",
    derivation_path=[raw_page, summary, planner],
)

try:
    enforce_taint_boundary(call)
except TaintBoundaryViolation as exc:
    print(f"BLOCKED: {exc}")
