# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-a-sanitizer-tool-that-returns-a-semantically-equivalent-but-freshly-attributed-value.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-a-sanitizer-tool-that-returns-a-semantically-equivalent-but-freshly-attributed-value.warrant.json
# Markdown SHA-256:   61b28d1a5b4c46e27463ca16e45f2596eece9438f5830fbdeb501070d7b072ff
# Code AST SHA-256:   a183a87c4957b7374260d42625f4c533543873b5553d9c3d7f13079af98e7cca
# Verified Classes:   TaintLaunderingError, Taint
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a sanitizer clears taint without destroying sink-relevant information."""


@dataclass(frozen=True)
class Taint:
    source: str          # e.g. "UNTRUSTED(web)", "UNTRUSTED(secret)", "TRUSTED(user)"
    ancestors: frozenset[str] = field(default_factory=frozenset)

    @property
    def is_clean(self) -> bool:
        return self.source.startswith("TRUSTED") or self.source == "CLEAN"


# A sanitizer is only allowed to *drop* ancestor edges if it satisfies a
# destruction predicate. Bijective encoders never qualify.
DESTRUCTION_PREDICATES = {
    "classify_enum",     # output is a label from a fixed enum
    "bounded_length",    # output alphabet strictly smaller than payload alphabet
    "rescan_clean",      # output re-scanned by taint-preserving detector
}


def apply_sanitizer(name: str, predicate: str, inp: Taint) -> Taint:
    if predicate not in DESTRUCTION_PREDICATES:
        raise TaintLaunderingError(
            f"sanitizer {name!r} claims predicate {predicate!r} which is not a "
            f"destruction predicate; it cannot clear taint"
        )
    # Even a valid predicate keeps the source label but may drop ancestors.
    return Taint(source=inp.source, ancestors=frozenset())


def check_sink(sink: str, arg: Taint, transitive_inputs: Iterable[Taint]) -> None:
    if not arg.is_clean:
        raise TaintLaunderingError(f"sink {sink!r} refused: argument tainted by {arg.source!r}")
    # Source-at-sink: walk the transitive input set, not just the current tag.
    for leaf in transitive_inputs:
        if not leaf.is_clean:
            raise TaintLaunderingError(
                f"sink {sink!r} refused: transitive input tainted by {leaf.source!r} "
                f"(laundering via a non-destructive sanitizer is blocked)"
            )


def demo() -> None:
    secret = Taint(source="UNTRUSTED(secret)")
    # base64_encode is bijective -> not a destruction predicate -> attempt to launder fails here.
    try:
        enc = apply_sanitizer("base64_encode", "bijective_encoding", secret)
    except TaintLaunderingError as e:
        print("blocked at sanitizer:", e)
        enc = Taint(source="UNTRUSTED(secret)", ancestors=frozenset({"read_file"}))

    # Even if a buggy sanitizer returned CLEAN, the sink walk catches the ancestor.
    try:
        check_sink("http_post", arg=Taint(source="CLEAN"), transitive_inputs=[enc])
    except TaintLaunderingError as e:
        print("blocked at sink:", e)


if __name__ == "__main__":
    demo()
