# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-sanitized-from-untrusted-by-construction-at-the-moment-an-llm-string-crosses-into-a-shell-sql-or-filesystem-executo.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-sanitized-from-untrusted-by-construction-at-the-moment-an-llm-string-crosses-into-a-shell-sql-or-filesystem-executo.warrant.json
# Markdown SHA-256:   9963aebf6260f0253e917b7b3b189bd95ed96b02bef3428ea4c630c240b83ee8
# Code AST SHA-256:   ac8622993279c863187cde7d383febb1d1f3865ea86aa9aa73af32d5ac3810fa
# Verified Classes:   TaintLaunderingError, TaintedValue
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import os
import sqlite3
import subprocess
from dataclasses import dataclass


class TaintLaunderingError(RuntimeError):
    """Raised when tainted model output is routed to a non-bindable sink
    or when a sink-scoped safety check is bypassed."""


@dataclass(frozen=True)
class TaintedValue:
    raw: str
    origin: str = "llm_output"

    def safe_for(self, sink: str) -> bool:
        # Taint is monotonic; no transformation clears it. Only named,
        # trusted parsers may produce a TRUSTED value, never this type.
        return False


def exec_shell(argv: list[str], value: TaintedValue) -> int:
    # Shell sink is bindable via argv array; the value must never enter
    # the command string. If a caller passes a string, refuse.
    if not isinstance(value, TaintedValue):
        raise TaintLaunderingError("shell sink received untyped value")
    if value.safe_for("shell"):
        raise TaintLaunderingError("tainted value claimed shell-safe; refusing")
    # value.raw is passed as a discrete argv element, never interpolated.
    return subprocess.run(argv + [value.raw], check=True).returncode


def exec_sql(conn: sqlite3.Connection, value: TaintedValue) -> list:
    # SQL sink is bindable via placeholder; identifiers are NOT bindable
    # and must be refused rather than escaped.
    if value.safe_for("sql"):
        raise TaintLaunderingError("tainted value claimed sql-safe; refusing")
    cur = conn.execute("SELECT * FROM records WHERE name = ?", (value.raw,))
    return cur.fetchall()


def exec_write(base_dir: str, value: TaintedValue) -> str:
    # Filesystem sink is bindable via openat-equivalent: validate the
    # basename and refuse anything that is not a plain relative name.
    if value.safe_for("path"):
        raise TaintLaunderingError("tainted value claimed path-safe; refusing")
    name = value.raw
    if os.path.isabs(name) or os.sep in name or name in ("", ".", ".."):
        raise TaintLaunderingError(
            f"tainted path {name!r} is not a plain basename; refusing"
        )
    target = os.path.join(base_dir, name)
    with open(target, "w", encoding="utf-8") as fh:
        fh.write("")
    return target
