# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-tool-return-normalization-in-runtime-taint-gated-invocation-policies.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-tool-return-normalization-in-runtime-taint-gated-invocation-policies.warrant.json
# Markdown SHA-256:   8e40d19224d50d72d2e3f1176e37220add67d0f048d3db3a1d695661cd07f2b9
# Code AST SHA-256:   0f6b1efbc537dd6101dc4dd0b03890887a4255de43ab1b3ff537b725d57eb7b9
# Verified Classes:   TaintViolation, Label, ToolContract, Tainted
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Callable, Iterable


class TaintViolation(RuntimeError):
    """Raised when a tool invocation would launder or leak tainted data."""


class Label(Enum):
    UNKNOWN = 0   # provenance not tracked — gated like SECRET
    PUBLIC = 1
    SECRET = 2


@dataclass(frozen=True)
class ToolContract:
    name: str
    clearance: Label
    # Arguments whose values flow into the return value. Empty tuple is a
    # claim of "no derivation" and is rejected unless verified_constant=True.
    derivation_sources: tuple[str, ...]
    # A declassification is only honored when the tool proves its output is a
    # constant function of the input's taint class (not of its content).
    declassifies: tuple[Label, Label] | None = None
    verified_constant: bool = False


@dataclass
class Tainted:
    value: Any
    labels: frozenset[Label] = field(default_factory=lambda: frozenset({Label.PUBLIC}))
    chain: tuple[str, ...] = ()

    def join(self, other: "Tainted", via: str) -> "Tainted":
        return Tainted(
            value=self.value,
            labels=self.labels | other.labels,
            chain=self.chain + other.chain + (via,),
        )


def join_labels(items: Iterable[Tainted]) -> frozenset[Label]:
    acc: frozenset[Label] = frozenset()
    for it in items:
        acc = acc | it.labels
    return acc


def invoke(
    contract: ToolContract,
    args: dict[str, Tainted],
    impl: Callable[..., Any],
) -> Tainted:
    # 1. Sink check: the tool's clearance must dominate every argument label.
    incoming = join_labels(args.values())
    if contract.clearance.value < max(l.value for l in incoming):
        raise TaintViolation(
            f"sink {contract.name!r} clearance={contract.clearance.name} "
            f"cannot receive labels={sorted(l.name for l in incoming)}"
        )

    # 2. Derivation-source declaration is mandatory. A tool that claims no
    #    derivation sources must be verified constant, or it is a laundering
    #    primitive by construction.
    if not contract.derivation_sources and not contract.verified_constant:
        raise TaintViolation(
            f"tool {contract.name!r} declares no derivation_sources and is not "
            f"verified_constant; refusing to invoke (laundering risk)"
        )

    raw = impl(**{k: v.value for k, v in args.items()})

    # 3. Label preservation across the return. Union all declared sources.
    source_labels: frozenset[Label] = frozenset()
    source_chain: tuple[str, ...] = ()
    for name in contract.derivation_sources:
        if name not in args:
            raise TaintViolation(
                f"tool {contract.name!r} declares derivation source {name!r} "
                f"but it was not supplied"
            )
        source_labels = source_labels | args[name].labels
        source_chain = source_chain + args[name].chain

    # 4. Declassification is honored only when the output is a constant
    #    function of the taint class. Length-preserving redaction violates
    #    this and must be caught here, not downstream.
    if contract.declassifies is not None:
        src, dst = contract.declassifies
        if src not in source_labels:
            raise TaintViolation(
                f"tool {contract.name!r} claims declassify {src.name}->{dst.name} "
                f"but source label absent from {sorted(l.name for l in source_labels)}"
            )
        if not contract.verified_constant:
            raise TaintViolation(
                f"tool {contract.name!r} claims declassification without a "
                f"verified-constant output contract; output may leak structure "
                f"(e.g. length, shape) of the source"
            )
        source_labels = (source_labels - {src}) | {dst}

    # 5. Untracked provenance is not clean provenance.
    if not source_labels:
        source_labels = frozenset({Label.UNKNOWN})

    return Tainted(
        value=raw,
        labels=source_labels,
        chain=source_chain + (contract.name,),
    )


# --- Demonstration of the laundering trace from the record ---

def _read_secret_store(key: str) -> str:
    return "hunter2-correct-horse"

def _redact_length_preserving(value: str) -> str:
    return f"[REDACTED-LEN-{len(value)}]"

def _send_email(to: str, body: str) -> str:
    return "sent"


read_contract = ToolContract(
    name="read_secret_store",
    clearance=Label.SECRET,
    derivation_sources=("key",),
)
redact_contract = ToolContract(
    name="redact_length_preserving",
    clearance=Label.SECRET,
    derivation_sources=("value",),
    # Attempted declassification with no verified-constant proof:
    declassifies=(Label.SECRET, Label.PUBLIC),
    verified_constant=False,
)
send_contract = ToolContract(
    name="send_email",
    clearance=Label.PUBLIC,
    derivation_sources=("body",),
)


def run_trace() -> None:
    secret = invoke(read_contract, {"key": Tainted("db_password")}, _read_secret_store)
    # The following call must fail: the redactor claims declassification but
    # cannot prove its output is independent of the secret's content.
    laundered = invoke(redact_contract, {"value": secret}, _redact_length_preserving)
    # Unreachable if the invariant holds; kept to show the leak path.
    invoke(send_contract, {"to": Tainted("ext@example.com"), "body": laundered}, _send_email)


if __name__ == "__main__":
    try:
        run_trace()
    except TaintViolation as exc:
        print(f"blocked: {exc}")
