# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-propagate-prompt-injection-taint-labels-across-an-agent-handoff-without-letting-a-trusted-sub-agent-launder-untrusted-bytes.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-propagate-prompt-injection-taint-labels-across-an-agent-handoff-without-letting-a-trusted-sub-agent-launder-untrusted-bytes.warrant.json
# Markdown SHA-256:   4b9122ea7a6b7363eca5b8df441a67705edd8bf149ad29fb2b7ee16d92baed69
# Code AST SHA-256:   2ddac07b8c9e56139f8896688a662255efebd0b7ff80b791ce5090083aeebc87
# Verified Classes:   Trust, IFCLabel, TaintLaunderingError, Envelope
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class Trust(str, Enum):
    TRUSTED = "TRUSTED"
    UNTRUSTED = "UNTRUSTED"


@dataclass(frozen=True)
class IFCLabel:
    trust: Trust
    origins: frozenset[str] = field(default_factory=frozenset)
    taint_ids: frozenset[str] = field(default_factory=frozenset)

    @staticmethod
    def clean() -> "IFCLabel":
        return IFCLabel(Trust.TRUSTED)

    @staticmethod
    def untrusted(origin: str, taint_id: str) -> "IFCLabel":
        return IFCLabel(Trust.UNTRUSTED, frozenset({origin}), frozenset({taint_id}))

    def join(self, other: "IFCLabel") -> "IFCLabel":
        # Taint dominates. No majority vote, no declassification here.
        trust = Trust.UNTRUSTED if Trust.UNTRUSTED in (self.trust, other.trust) else Trust.TRUSTED
        return IFCLabel(trust, self.origins | other.origins, self.taint_ids | other.taint_ids)


class TaintLaunderingError(RuntimeError):
    """Raised when a handoff would recompute trust from principal identity
    instead of joining payload provenance, or when a tainted argument reaches
    an exfiltration sink without an authorized declassification."""


EXFIL_SINKS = {"send_email", "http_post", "write_external"}


@dataclass
class Envelope:
    sender: str
    receiver: str
    payload: str
    ifc_label: IFCLabel | None


def handoff(env: Envelope) -> Envelope:
    # Fail closed: an envelope with no label is not implicitly trusted.
    if env.ifc_label is None:
        raise TaintLaunderingError(
            f"handoff {env.sender}->{env.receiver} carries no ifc_label; "
            f"refusing to infer trust from principal identity"
        )
    return env


def combine_inputs(envs: Iterable[Envelope]) -> IFCLabel:
    label = IFCLabel.clean()
    for e in envs:
        if e.ifc_label is None:
            raise TaintLaunderingError(f"unlabeled input from {e.sender}")
        label = label.join(e.ifc_label)
    return label


def invoke_tool(tool: str, arg_label: IFCLabel, arg: str) -> None:
    if tool in EXFIL_SINKS and arg_label.trust is Trust.UNTRUSTED:
        raise TaintLaunderingError(
            f"tool '{tool}' blocked: argument tainted by {sorted(arg_label.taint_ids)} "
            f"from origins {sorted(arg_label.origins)}"
        )
    # ... dispatch ...


# Reproduces the observed laundering trace.
retriever_out = Envelope("retriever", "orchestrator", "ticket body...",
                         IFCLabel.untrusted("crm_fetch", "T-4471"))
handoff(retriever_out)

# Correct: summarizer output joins input label; emitter identity is irrelevant.
summarizer_out = Envelope("summarizer", "planner", "summary preserving directive...",
                          combine_inputs([retriever_out]))
handoff(summarizer_out)

try:
    invoke_tool("send_email", summarizer_out.ifc_label, "customer table")
except TaintLaunderingError as e:
    print(f"contained: {e}")
