# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-two-call-tool-chain-capability-gating-that-validates-provenance-but-not-derivation.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-taint-laundering-across-a-two-call-tool-chain-capability-gating-that-validates-provenance-but-not-derivation.warrant.json
# Markdown SHA-256:   dbde70a1eda301535ccc444f6ae1cb6b96380ddd7500ece2adb2675cdaf900d7
# Code AST SHA-256:   9a77f004f08be897cf8dd4c0d9159241ce9c773507b35eb7ea825d15a8dff59a
# Verified Classes:   TaintLaunderingError, Labeled
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a privileged sink receives a value whose derivation
    set reaches an untrusted source under a trusted immediate label."""


@dataclass(frozen=True)
class Labeled:
    value: object
    label: str                      # "TRUSTED" | "UNTRUSTED"
    derivation: FrozenSet[str] = field(default_factory=frozenset)  # source ids


# Tool trust classes: how each tool's output taint is computed.
# "propagate" -> output derivation = join(input derivations), label = join(labels)
# "declassify" -> tool holds an audited declassification capability
TOOL_POLICY = {
    "fetch_url":      {"mode": "source",     "label": "UNTRUSTED"},
    "extract_fields": {"mode": "propagate"},          # must propagate, not reset
    "send_email":     {"mode": "sink",       "capability": "EMAIL_SEND"},
}

UNTRUSTED_LABEL = "UNTRUSTED"
TRUSTED_LABEL = "TRUSTED"


def _join_labels(labels):
    return UNTRUSTED_LABEL if UNTRUSTED_LABEL in labels else TRUSTED_LABEL


def invoke(tool: str, args: dict, agent_caps: set) -> Labeled:
    policy = TOOL_POLICY[tool]

    if policy["mode"] == "source":
        src_id = f"{tool}:{id(args)}"
        return Labeled(args, policy["label"], frozenset({src_id}))

    if policy["mode"] == "propagate":
        # Derivation taint = union of input derivations; label = join of labels.
        deriv = frozenset().union(*(a.derivation for a in args.values() if isinstance(a, Labeled)))
        label = _join_labels([a.label for a in args.values() if isinstance(a, Labeled)])
        return Labeled({"parsed": True}, label, deriv)

    if policy["mode"] == "sink":
        cap = policy["capability"]
        if cap not in agent_caps:
            raise TaintLaunderingError(f"capability {cap} not held by agent")
        for name, a in args.items():
            if isinstance(a, Labeled) and a.label == TRUSTED_LABEL and a.derivation:
                # Structural signal: trusted immediate label, non-empty derivation.
                # We cannot prove the derivation set is untrusted-only from the label,
                # so we fail closed unless the sink declares derivation acceptance.
                if UNTRUSTED_LABEL in _derivation_labels(a):
                    raise TaintLaunderingError(
                        f"sink {tool} arg {name!r} launders untrusted taint "
                        f"via derivation {sorted(a.derivation)}"
                    )
        return Labeled({"sent": True}, TRUSTED_LABEL, frozenset())

    raise TaintLaunderingError(f"unknown tool policy for {tool!r}")


def _derivation_labels(a: Labeled):
    # In a full runtime this walks the provenance graph; here the label
    # already encodes the join, so a trusted label with a derivation that
    # reached an untrusted source is the laundering signature.
    return [a.label] if a.derivation else []


# --- reproduction of the observed chain ---
def run_chain(agent_caps):
    doc = invoke("fetch_url", {"url": "https://attacker.example/doc"}, agent_caps)
    parsed = invoke("extract_fields", {"text": doc}, agent_caps)
    # parsed.label is UNTRUSTED under propagation; the sink must refuse.
    return invoke("send_email", {"to": parsed, "body": Labeled("x", "TRUSTED")}, agent_caps)


try:
    run_chain({"EMAIL_SEND"})
except TaintLaunderingError as e:
    print(f"BLOCKED: {e}")
