# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-leak-tainted-data-through-a-clean-tool-return-the-side-channel-closure-invariant-in-taint-aware-sandboxing.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-leak-tainted-data-through-a-clean-tool-return-the-side-channel-closure-invariant-in-taint-aware-sandboxing.warrant.json
# Markdown SHA-256:   01e9290f7ee121cf4f679e10808ad6874d84a309e760cb7429e342e49ece4abe
# Code AST SHA-256:   5ce01b4ffb3e0eacd7f4a1125dcbb0d2f55ff9d18f81cb0e7683813936b5fe82
# Verified Classes:   Tainted, TaintClosureError
# Defensive Guards:   1 fail-closed invariants (zero external deps)

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

# Lattice: PUBLIC < UNTRUSTED < SECRET. Join is max.
_RANK = {"PUBLIC": 0, "UNTRUSTED": 1, "SECRET": 2}


def join(*labels: str) -> str:
    return max(labels, key=lambda l: _RANK[l])


@dataclass
class Tainted:
    value: Any
    label: str
    provenance: frozenset = field(default_factory=frozenset)


class TaintClosureError(RuntimeError):
    """Raised when a derived value would reach an egress sink without
    carrying the join of its input labels (label laundering)."""


# Declared declassifiers: tool name -> predicate on call args.
DECLASSIFIERS: dict[str, Callable[[dict], bool]] = {
    "aggregate_k": lambda a: a.get("k", 0) >= 5,
}


def invoke(tool: str, args: dict[str, Tainted], impl: Callable) -> Tainted:
    in_label = join(*(a.label for a in args.values()), "PUBLIC")
    raw = impl({k: v.value for k, v in args.items()})
    if tool in DECLASSIFIERS and DECLASSIFIERS[tool](args):
        out_label = "PUBLIC"  # audited, entropy-bounded declassification
    else:
        out_label = in_label  # closure: derivation preserves taint
    return Tainted(raw, out_label, frozenset().union(*(a.provenance for a in args.values())))


def egress(sink: str, payload: Tainted) -> None:
    if sink in {"http_post", "send_email", "write_file"} and payload.label != "PUBLIC":
        raise TaintClosureError(
            f"sink {sink!r} refused: payload label={payload.label!r} "
            f"(provenance={sorted(payload.provenance)}); "
            "derived value still carries taint — declassify via audited tool first"
        )
    # ... perform the actual egress ...


# --- the failing trace, now bounded ---
def run_trace() -> None:
    secret = Tainted("sk-live-abc", "SECRET", frozenset({"env:X-Billing-Key"}))
    digest = invoke("sha256", {"x": secret}, lambda a: __import__("hashlib").sha256(a["x"].encode()).hexdigest())
    # digest.label == "SECRET" because sha256 is NOT a declared declassifier.
    egress("http_post", digest)  # raises TaintClosureError
