# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-nested-tool-call-authority-in-agentic-rpc-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-taint-laundering-through-nested-tool-call-authority-in-agentic-rpc-chains.warrant.json
# Markdown SHA-256:   5a77742da5c4b3c7b37727cf8dfeba258b02d8240f4629d23784fa9b95999f56
# Code AST SHA-256:   b279c2167040e8a1b370b5bd43a91afb49a6b2ec5a6fe8341ccaa60ede01917c
# Verified Classes:   TaintLaunderingError, Provenance, Frame
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a mutating call's transitive argument taint is non-empty
    and no warrant is scoped to the offending taint origin."""
    pass


@dataclass(frozen=True)
class Provenance:
    origin: str  # e.g. "untrusted:doc-42"
    token: str   # broker-stamped content hash, unforgeable by tools


@dataclass
class Frame:
    caller_taint: frozenset[str] = frozenset()
    args: dict = field(default_factory=dict)


def resolve_arg_taint(args: dict, provenance_store: dict) -> frozenset[str]:
    """Reconstruct taint from per-value provenance tokens. A value with no
    token is treated as maximally tainted (fail closed)."""
    taint: set[str] = set()
    for value in args.values():
        token = getattr(value, "provenance_token", None)
        if token is None:
            taint.add("unattributed")  # missing lineage == suspect
            continue
        prov: Optional[Provenance] = provenance_store.get(token)
        if prov is None:
            taint.add("unattributed")
        else:
            taint.add(prov.origin)
    return frozenset(taint)


def admit_mutating_call(
    frame: Frame,
    provenance_store: dict,
    warrant_origins: frozenset[str],
) -> None:
    """Invariant: taint is monotone across the call graph.
    Union of caller taint and argument taint must be covered by a warrant."""
    effective_taint = frame.caller_taint | resolve_arg_taint(
        frame.args, provenance_store
    )
    uncovered = effective_taint - warrant_origins
    if uncovered:
        raise TaintLaunderingError(
            f"mutating call blocked: un-warranted taint {sorted(uncovered)} "
            f"reached frame via nested RPC; provenance token missing or "
            f"unstripped"
        )
    # admitted: caller may proceed to commit


# --- reproduction of the observed exploit, now bounded ---
store = {
    "tok-abc": Provenance(origin="untrusted:doc-42", token="tok-abc"),
}
# planner's frame: caller taint known, arg carries its token
planner_args = {"field": type("V", (), {"provenance_token": "tok-abc"})()}
planner_frame = Frame(caller_taint=frozenset({"untrusted:doc-42"}),
                      args=planner_args)

# fetch_and_summarize's nested frame: caller_taint reset to empty (the bug),
# but the argument token survives serialization and is re-resolved here.
nested_frame = Frame(caller_taint=frozenset(), args=planner_args)

admit_mutating_call(nested_frame, store, warrant_origins=frozenset())
# -> raises TaintLaunderingError: "untrusted:doc-42" is un-warranted,
#    proving the laundering path is closed even when caller trust is reset.
