# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-tainted-memory-across-a-tool-call-boundary-rather-than-sanitize-it-in-place.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-quarantine-tainted-memory-across-a-tool-call-boundary-rather-than-sanitize-it-in-place.warrant.json
# Markdown SHA-256:   9b55d8a9937a9d977829deafc4abe213abfa221292f77fbf6e6eea914374cbb8
# Code AST SHA-256:   64b9ed287764e8003e898dbb793701b9c542f0c5beede3e8228971d837464b9c
# Verified Classes:   TaintLaunderingError, Tainted
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class TaintLaunderingError(RuntimeError):
    """Raised when an untrusted-derived value reaches a privileged sink
    without explicit declassification."""
    pass


@dataclass
class Tainted:
    value: Any
    origin: str            # e.g. "UNTRUSTED:vendor_endpoint"
    history: list = field(default_factory=list)

    @property
    def trusted(self) -> bool:
        return self.origin.startswith("TRUSTED")


# Sinks that mutate external state or cross a privilege boundary.
PRIVILEGED_SINKS = {"calendar.update", "send_email", "fs.delete", "payment.charge"}


def guarded_tool_call(sink: str, args: dict, declassified: set) -> dict:
    """Enforce the sink-side provenance invariant.

    A privileged sink may only receive arguments that are either
    (a) trusted-origin, or (b) explicitly declassified by a human/policy step.
    Paraphrase is irrelevant: we check labels, not lexical form.
    """
    if sink in PRIVILEGED_SINKS:
        for name, arg in args.items():
            if isinstance(arg, Tainted) and not arg.trusted:
                key = (sink, name, arg.origin)
                if key not in declassified:
                    raise TaintLaunderingError(
                        f"Argument '{name}' to privileged sink '{sink}' derives "
                        f"from {arg.origin} (history={arg.history}) and was not "
                        f"declassified. Quarantining call rather than executing."
                    )
    return {"sink": sink, "args": {k: (v.value if isinstance(v, Tainted) else v)
                                   for k, v in args.items()}}


def demo():
    # Footer instruction from a vendor document, paraphrased by the model
    # into a calendar write with an inferred elevated scope.
    inferred_date = Tainted(
        value="2025-09-01",
        origin="UNTRUSTED:vendor_endpoint",
        history=["fetch_document -> footer instruction -> model inference"],
    )
    scope = Tainted(
        value="write",
        origin="UNTRUSTED:archive_mirror",
        history=["fetch_url(named in untrusted text) -> model inference"],
    )

    # No declassification performed: this must be blocked, not sanitized.
    guarded_tool_call(
        "calendar.update",
        {"date": inferred_date, "scope": scope},
        declassified=set(),
    )


if __name__ == "__main__":
    demo()
