# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-injection-taint-as-a-call-time-argument-invariant-rather-than-a-prompt-level-filter.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-injection-taint-as-a-call-time-argument-invariant-rather-than-a-prompt-level-filter.warrant.json
# Markdown SHA-256:   7d78fbeb940228237fa1015d5107788f41ac0b9cb9c098535d88a39cb97884c4
# Code AST SHA-256:   601e371da128d96413d4a73b0879ab252118552cfe504d05f2b6cd0d1c757696
# Verified Classes:   TaintViolation, Tainted
# Defensive Guards:   3 fail-closed invariants (zero external deps)

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


class TaintViolation(RuntimeError):
    """Raised when a tainted value reaches a sink without explicit declassification."""


@dataclass(frozen=True)
class Tainted:
    value: Any
    labels: frozenset[str] = field(default_factory=frozenset)

    def __post_init__(self) -> None:
        if not isinstance(self.labels, frozenset):
            raise TaintViolation("labels must be a frozenset; mutable taint is a laundering seam")


TAINTED_SINKS = {"read_file", "write_file", "send_email", "shell", "fetch_url"}
DECLASSIFY_LOG: list[tuple[Any, str, str]] = []


def concat(parts: Iterable[Tainted]) -> Tainted:
    parts = list(parts)
    if not parts:
        return Tainted("", frozenset())
    labels: frozenset[str] = frozenset()
    for p in parts:
        labels = labels | p.labels
    return Tainted("".join(str(p.value) for p in parts), labels)


def declassify(t: Tainted, reason: str, approver: str) -> Tainted:
    if not reason or not approver:
        raise TaintViolation("declassification requires non-empty reason and approver")
    DECLASSIFY_LOG.append((t.value, reason, approver))
    return Tainted(t.value, frozenset())


def dispatch(tool: str, args: dict[str, Tainted]) -> None:
    if tool not in TAINTED_SINKS:
        return
    for name, arg in args.items():
        if arg.labels:
            raise TaintViolation(
                f"tool={tool!r} arg={name!r} carries taint {sorted(arg.labels)}; "
                f"value={arg.value!r} reached a sink without declassify()"
            )


def build_and_call(tool: str, template: str, field_value: Tainted) -> None:
    # Interpolation is the seam where identity-keyed taint is lost.
    arg = concat([Tainted(template, frozenset()), field_value])
    dispatch(tool, {"path": arg})


if __name__ == "__main__":
    retrieved = Tainted("../../etc/passwd", frozenset({"SOURCE:web:untrusted"}))
    try:
        build_and_call("read_file", "root={}", retrieved)
    except TaintViolation as exc:
        print(f"blocked at call time: {exc}")
