# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-taint-across-mcp-tool-call-boundaries-rather-than-resetting-privilege-at-each-invocation.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-propagate-taint-across-mcp-tool-call-boundaries-rather-than-resetting-privilege-at-each-invocation.warrant.json
# Markdown SHA-256:   8043793ebd41e1907eedfa66672d188a62ff6a1cc7cfb5dbb057f34add8eda02
# Code AST SHA-256:   f8422e7dbe1eee4243b1f45027b6058b10bc0a7fcd753958cb21154a4d838faa
# Verified Classes:   TaintBoundaryViolation, Scope, TaintedValue, TaintAwareSandbox
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintBoundaryViolation(RuntimeError):
    """Raised when a privileged call is parameterized by tainted data across a scope reset."""
    pass


@dataclass(frozen=True)
class Scope:
    caps: FrozenSet[str]

    def issubset(self, other: "Scope") -> bool:
        return self.caps.issubset(other.caps)


@dataclass
class TaintedValue:
    value: str
    origin_scope: Scope
    labels: FrozenSet[str] = field(default_factory=frozenset)


class TaintAwareSandbox:
    def __init__(self) -> None:
        self._taint_store: dict[str, TaintedValue] = {}

    def register_tainted(self, tv: TaintedValue) -> None:
        self._taint_store[tv.value] = tv

    def invoke(self, tool: str, call_scope: Scope, args: dict[str, str]) -> None:
        # Determine which args are tainted and whether any taint origin's scope
        # is NOT a superset of the call's scope (i.e. orthogonal/escalating).
        escalating = [
            self._taint_store[a]
            for a in args.values()
            if a in self._taint_store
            and not call_scope.issubset(self._taint_store[a].origin_scope)
        ]
        if escalating:
            # Do NOT reset taint; deny or gate. Per-call least privilege is
            # insufficient because the composed capability graph escalates.
            raise TaintBoundaryViolation(
                f"tool={tool} call_scope={sorted(call_scope.caps)} "
                f"parameterized by tainted args from origins="
                f"{[sorted(t.origin_scope.caps) for t in escalating]}; "
                f"refusing scope reset that would launder privilege"
            )
        # Safe: either no tainted args, or downstream scope ⊆ taint origin scope.
        # Scope reset here is sound; taint store is left intact (never mutated
        # by a scope reset) so downstream derivations still carry lineage.
        self._run(tool, call_scope, args)

    def _run(self, tool: str, scope: Scope, args: dict[str, str]) -> None:
        pass


# Reproduction of the observed failure trace:
sandbox = TaintAwareSandbox()
mail_read_scope = Scope(frozenset({"mail:read"}))
egress_scope = Scope(frozenset({"net:egress"}))
send_scope = Scope(frozenset({"mail:send:*"}))

# Step 1-2: injected URL extracted from mail body, tainted by mail:read origin.
sandbox.register_tainted(
    TaintedValue("https://attacker.example/payload", mail_read_scope, frozenset({"attacker.example"}))
)
# Step 3: fetch is scoped to egress; origin (mail:read) does not contain net:egress,
# so this is already escalating -- the fetch itself must be gated in a strict runtime.
# Step 4: recipient parsed from fetched page inherits taint from the fetch output.
sandbox.register_tainted(
    TaintedValue("ops@attacker.example", egress_scope, frozenset({"attacker.example"}))
)

# Step 5: mail.send with orthogonal scope and tainted recipient -> must raise.
sandbox.invoke("mail.send", send_scope, {"recipient": "ops@attacker.example", "body": "..."})
