# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-taint-label-inheritance-across-a-tool-call-chain-as-a-monotonic-lattice-rather-than-a-per-call-advisory-t.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-taint-label-inheritance-across-a-tool-call-chain-as-a-monotonic-lattice-rather-than-a-per-call-advisory-t.warrant.json
# Markdown SHA-256:   eb0852f9e6c6320bf38c9bddc5ff693b0f1809fa789117ddbef1be56790e60cc
# Code AST SHA-256:   d0a2b1bce7a91baba0e6607bbcd61391720539bf97b48e3419f3eff1c053b6dd
# Verified Classes:   TaintLatticeViolation, Label, Tainted, ToolSpec, ChainState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

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


class TaintLatticeViolation(RuntimeError):
    """Raised when a tool call would cross a privilege boundary with a label
    that is lower than the join of its transitive inputs (i.e. laundering)."""


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

    @classmethod
    def join(cls, *labels: "Label") -> "Label":
        return cls(max(labels, default=cls.TRUSTED))


# Tools whose output is a *constant-bounded* function of input may declassify.
# Anything that preserves attacker-controlled entropy must NOT appear here.
DECLASSIFIERS: frozenset[str] = frozenset({"int_range_cast", "enum_lookup"})


@dataclass
class Tainted:
    value: Any
    label: Label


@dataclass
class ToolSpec:
    name: str
    max_egress: Label  # highest taint this tool may be invoked with
    is_transform: bool = True


@dataclass
class ChainState:
    # label per produced value, keyed by a stable id
    labels: dict[str, Label] = field(default_factory=dict)

    def record(self, value_id: str, label: Label) -> None:
        # monotonic: a value's label may only rise
        self.labels[value_id] = Label.join(self.labels.get(value_id, Label.TRUSTED), label)


def invoke(
    state: ChainState,
    spec: ToolSpec,
    input_ids: list[str],
    output_id: str,
    *,
    declared_declassify: bool = False,
) -> None:
    # join over every transitive input the call consumed
    effective = Label.join(*(state.labels.get(i, Label.TRUSTED) for i in input_ids))

    if effective > spec.max_egress:
        raise TaintLatticeViolation(
            f"tool {spec.name!r} has max_egress={spec.max_egress.name} "
            f"but call consumed taint {effective.name} via {input_ids}"
        )

    if declared_declassify and spec.name not in DECLASSIFIERS:
        raise TaintLatticeViolation(
            f"tool {spec.name!r} attempted declassification but is not "
            f"in the reviewed DECLASSIFIERS registry"
        )

    out_label = effective
    if declared_declassify:
        # only sound for constant-bounded transforms; registry gate above
        out_label = Label.TRUSTED

    state.record(output_id, out_label)


# --- trace of the laundering attack ---
def run_trace() -> None:
    state = ChainState()
    state.record("body_B", Label.UNTRUSTED)          # fetch_page output

    # json_parse is a trusted *tool* but a lossy *transform*: it must inherit.
    invoke(
        state,
        ToolSpec(name="json_parse", max_egress=Label.UNTRUSTED),
        input_ids=["body_B"],
        output_id="dict_D",
    )  # dict_D -> UNTRUSTED

    # http_post has max_egress=INTERNAL; the join now blocks it.
    try:
        invoke(
            state,
            ToolSpec(name="http_post", max_egress=Label.INTERNAL),
            input_ids=["dict_D"],
            output_id="resp",
        )
    except TaintLatticeViolation as exc:
        print(f"blocked: {exc}")
        raise


if __name__ == "__main__":
    try:
        run_trace()
    except TaintLatticeViolation:
        pass
