# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-enforce-taint-provenance-across-a-sandbox-boundary-when-an-mcp-tool-response-is-partially-trusted.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-enforce-taint-provenance-across-a-sandbox-boundary-when-an-mcp-tool-response-is-partially-trusted.warrant.json
# Markdown SHA-256:   1e206d0d124641a1243cf5a7d7d8d71e9da18a26e727e2576e573d35557b0672
# Code AST SHA-256:   1e77e49c765abde21f80d263fb6ad6df26a147ba397b9a6eee88651e27dfe30c
# Verified Classes:   TaintLaunderingError, Label, Span, TaintSandbox
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, Optional


class TaintLaunderingError(RuntimeError):
    """Raised when a declassification would lower a container below its children's join,
    or when a witness minted for one sink is reused for another."""


class Label(IntEnum):
    TRUSTED = 0
    UNTRUSTED = 1

    @classmethod
    def join(cls, a: "Label", b: "Label") -> "Label":
        # Least upper bound: any untrusted child taints the parent.
        return cls(max(int(a), int(b)))


@dataclass
class Span:
    path: str
    label: Label
    witnesses: Dict[str, str] = field(default_factory=dict)  # sink -> witness kind


class TaintSandbox:
    def __init__(self) -> None:
        self._spans: Dict[str, Span] = {}

    def ingest(self, path: str, label: Label) -> None:
        self._spans[path] = Span(path=path, label=label)

    def _children(self, container: str) -> list[Span]:
        prefix = container.rstrip("/") + "/"
        return [s for p, s in self._spans.items() if p.startswith(prefix)]

    def container_label(self, container: str) -> Label:
        # Invariant: container taint = join over children, never the meet.
        label = self._spans.get(container, Span(container, Label.TRUSTED)).label
        for child in self._children(container):
            label = Label.join(label, child.label)
        return label

    def declassify(self, path: str, sink: str, witness_kind: str) -> None:
        span = self._spans.get(path)
        if span is None:
            raise TaintLaunderingError(f"unknown span {path!r}")
        # Sink-scoped witness: a shape witness cannot authorize a path sink.
        required = {"read_file": "path_safety", "exec": "command_safety",
                    "http_fetch": "url_safety"}
        if required.get(sink) != witness_kind:
            raise TaintLaunderingError(
                f"witness {witness_kind!r} does not authorize sink {sink!r} for {path!r}")
        span.witnesses[sink] = witness_kind
        span.label = Label.TRUSTED
        # Enforce join direction: a de-tainted child must not sit under a
        # container that is now more trusted than the child's siblings require.
        parent = path.rsplit("/", 1)[0] if "/" in path else None
        if parent is not None:
            recomputed = self.container_label(parent)
            stored = self._spans.get(parent)
            if stored is not None and recomputed > stored.label:
                # Container must be raised, never silently lowered by a child.
                stored.label = recomputed

    def authorize(self, path: str, sink: str) -> None:
        span = self._spans.get(path)
        if span is None:
            raise TaintLaunderingError(f"unregistered span {path!r}")
        if span.label == Label.UNTRUSTED or sink not in span.witnesses:
            raise TaintLaunderingError(
                f"span {path!r} is {span.label.name} for sink {sink!r}; refusing")


# --- Reproduction of the observed failure ---
sb = TaintSandbox()
sb.ingest("entries", Label.UNTRUSTED)
sb.ingest("entries/0/name", Label.UNTRUSTED)
sb.ingest("entries/0/size", Label.UNTRUSTED)

# Shape validation of `size` declassifies only that span, for no sink.
sb._spans["entries/0/size"].label = Label.TRUSTED

# The buggy path: declassifying the container from a shape witness.
try:
    sb.declassify("entries", sink="read_file", witness_kind="shape")
except TaintLaunderingError as e:
    print("blocked container laundering:", e)

# The buggy path: using a shape witness to authorize a path sink.
try:
    sb.declassify("entries/0/name", sink="read_file", witness_kind="shape")
except TaintLaunderingError as e:
    print("blocked sink/witness mismatch:", e)

# Correct path: mint a path-safety witness, then declassify for read_file only.
sb.declassify("entries/0/name", sink="read_file", witness_kind="path_safety")
sb.authorize("entries/0/name", "read_file")

# And the sibling `size` is still untrusted for read_file.
try:
    sb.authorize("entries/0/size", "read_file")
except TaintLaunderingError as e:
    print("sibling correctly refused:", e)
