# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-re-evaluate-an-egress-allowlist-decision-the-taint-laundering-gap-in-per-tool-call-policy-enforcement.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-re-evaluate-an-egress-allowlist-decision-the-taint-laundering-gap-in-per-tool-call-policy-enforcement.warrant.json
# Markdown SHA-256:   2ca63a8356b03bd553d515d1527f0273e78223cb14495779cbeb8392eeb64d66
# Code AST SHA-256:   5fdc3c12b8b818eff82e98ec0bab7c6c41a965ab62be9bf2eb29c2047b15dd99
# Verified Classes:   Taint, TaintLaunderingError, EgressDecision, EgressGate
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Any


class Taint(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1


class TaintLaunderingError(RuntimeError):
    """Raised when a cached egress allow is reused for a more-tainted call."""


@dataclass(frozen=True)
class EgressDecision:
    tool: str
    destination: str
    schema_hash: str
    taint_class: Taint
    allowed: bool


@dataclass
class EgressGate:
    # Keyed on (tool, destination, schema_hash, taint_class) -- taint in the key.
    _cache: dict[tuple[str, str, str, Taint], EgressDecision] = field(default_factory=dict)

    def _recompute_taint(self, args: dict[str, Any]) -> Taint:
        # Provenance is attached per-argument by the tool layer; recompute, never inherit.
        level = Taint.TRUSTED
        for value in args.values():
            prov = getattr(value, "provenance", "TRUSTED")
            if prov == "UNTRUSTED":
                level = Taint.UNTRUSTED
        return level

    def decide(
        self,
        tool: str,
        destination: str,
        schema_hash: str,
        args: dict[str, Any],
        policy_allows: bool,
    ) -> EgressDecision:
        current_taint = self._recompute_taint(args)
        key = (tool, destination, schema_hash, current_taint)

        if key in self._cache:
            cached = self._cache[key]
            # Defensive: if a caller ever constructs a key with a stale taint,
            # the decision's taint_class must match the current call's taint.
            if cached.taint_class < current_taint:
                raise TaintLaunderingError(
                    f"cached allow for {tool}->{destination} was evaluated at "
                    f"taint={cached.taint_class.name} but current call is "
                    f"taint={current_taint.name}; refusing to launder taint"
                )
            return cached

        # Policy that inspects content/provenance must reject UNTRUSTED egress.
        allowed = policy_allows and current_taint == Taint.TRUSTED
        decision = EgressDecision(tool, destination, schema_hash, current_taint, allowed)
        self._cache[key] = decision
        return decision


def enforce_egress(
    gate: EgressGate,
    tool: str,
    destination: str,
    schema_hash: str,
    args: dict[str, Any],
    policy_allows: bool,
) -> None:
    decision = gate.decide(tool, destination, schema_hash, args, policy_allows)
    if not decision.allowed:
        raise TaintLaunderingError(
            f"egress denied: {tool}->{destination} carries taint="
            f"{decision.taint_class.name} (schema={schema_hash})"
        )
