# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-tainted-label-through-a-tool-s-return-value-schema.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-launders-a-tainted-label-through-a-tool-s-return-value-schema.warrant.json
# Markdown SHA-256:   98c3761680f3f726a288aa23531e00ace41338a8cc6e5e62ff1fb5d623f8a581
# Code AST SHA-256:   b3e9bbd9afc846bd93e08ffa9e085b92d10639b98fbea80156be5aeb77495e11
# Verified Classes:   TaintLaunderingError, Label, ToolSpec
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when a tool return would lower the taint of its inputs without
    an explicit, policy-gated declassification."""


@dataclass(frozen=True)
class Label:
    untrusted: bool
    sources: frozenset[str] = field(default_factory=frozenset)

    def join(self, other: "Label") -> "Label":
        return Label(
            untrusted=self.untrusted or other.untrusted,
            sources=self.sources | other.sources,
        )


TRUSTED = Label(untrusted=False)
UNTRUSTED = Label(untrusted=True, sources=frozenset({"external"}))


@dataclass
class ToolSpec:
    name: str
    declared_trust: Label
    # Fields the tool is permitted to declassify, with a written basis.
    declassifiable_fields: frozenset[str] = frozenset()
    declassification_basis: str = ""


def propagate_return_label(
    spec: ToolSpec,
    input_labels: list[Label],
    returned_fields: dict[str, Any],
) -> dict[str, Label]:
    """Compute the label of every field in a tool's return value.

    Invariant: field_label >= spec.declared_trust JOIN (join of all input labels),
    unless the field is explicitly listed in spec.declassifiable_fields AND a
    non-empty declassification_basis is present.
    """
    input_join = TRUSTED
    for lbl in input_labels:
        input_join = input_join.join(lbl)

    floor = spec.declared_trust.join(input_join)
    out: dict[str, Label] = {}

    for fname in returned_fields:
        if not floor.untrusted:
            out[fname] = floor
            continue
        if fname in spec.declassifiable_fields and spec.declassification_basis:
            # Explicit, audited declassification: label drops to declared trust.
            out[fname] = spec.declared_trust
            continue
        # Implicit declassification attempt — refuse.
        raise TaintLaunderingError(
            f"tool {spec.name!r} would launder untrusted input into field "
            f"{fname!r} (input sources: {sorted(input_join.sources)}); "
            f"register an explicit declassification basis or propagate the label"
        )

    return out


# --- Demonstration of the failure and the guard -----------------------------

extract_amount = ToolSpec(
    name="extract_amount",
    declared_trust=TRUSTED,  # code is internal; data is not
    declassifiable_fields=frozenset(),  # no basis registered -> must propagate
)

email_label = UNTRUSTED
helper_input_labels = [email_label]
helper_return = {"amount": 9999.0, "currency": "USD", "confidence": 0.41}

try:
    labels = propagate_return_label(extract_amount, helper_input_labels, helper_return)
    # If we reach here, the sink gate sees UNTRUSTED on `amount` and blocks
    # issue_refund(amount=9999.0).
    if labels["amount"].untrusted:
        raise TaintLaunderingError(
            "issue_refund blocked: amount carries untrusted provenance "
            f"{sorted(labels['amount'].sources)}"
        )
except TaintLaunderingError as e:
    # Correct behavior: the refund is never issued.
    print(f"BLOCKED: {e}")
