# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-segment-boundary-when-a-least-privilege-capability-token-is-re-minted-from-a-sanitized-prompt-se.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-across-a-segment-boundary-when-a-least-privilege-capability-token-is-re-minted-from-a-sanitized-prompt-se.warrant.json
# Markdown SHA-256:   372d1d8a4fd6e2f479a0bf2d9b09fd31d35a96c51cfd5de1494b2cd8439520b6
# Code AST SHA-256:   da9b060ee5a32bc06d3f311c9014292233f564cdd7584afec30044b4ec7c295a
# Verified Classes:   TaintLaunderingError, Segment
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Iterable


class TaintLaunderingError(RuntimeError):
    """Raised when a segment's minted scopes exceed its derivation-taint floor."""


@dataclass(frozen=True)
class Segment:
    seg_id: str
    role: str                      # "SYSTEM" | "USER" | "TOOL_RESULT" | "AGENT_INTERNAL"
    taint: frozenset[str]          # intrinsic taint, e.g. {"untrusted_remote"}
    inputs: tuple[str, ...] = ()   # derivation edges into upstream segments


ROLE_CEILING = {
    "SYSTEM":         frozenset({"read:scratch", "fs.write", "net.post"}),
    "USER":           frozenset({"read:scratch", "net.post"}),
    "TOOL_RESULT":    frozenset({"read:scratch"}),
    "AGENT_INTERNAL": frozenset({"read:scratch", "fs.write", "net.post"}),
}

# Types whose values cannot carry an executable payload; taint may be dropped.
DROPPABLE_TYPES = frozenset({"int", "bool", "uuid", "enum_static"})


def effective_taint(seg: Segment, graph: dict[str, Segment]) -> frozenset[str]:
    """Taint monotonicity: union of intrinsic taint and all upstream taint."""
    acc = set(seg.taint)
    for up_id in seg.inputs:
        acc |= effective_taint(graph[up_id], graph)
    return frozenset(acc)


def mint(seg: Segment, graph: dict[str, Segment],
         sanitized_fields: Iterable[tuple[str, str]] = ()) -> frozenset[str]:
    """
    Mint scopes at min(role_ceiling, derivation_floor).
    `sanitized_fields` is (field_name, declared_type) pairs certified by a
    typed transform; only DROPPABLE_TYPES may reduce the taint floor.
    """
    taint = effective_taint(seg, graph)

    dropped = {f for f, ty in sanitized_fields if ty in DROPPABLE_TYPES}
    residual = taint  # free-text fields retain taint unconditionally

    ceiling = ROLE_CEILING[seg.role]

    if residual:
        # Any residual taint caps scopes at the untrusted floor.
        floor = ROLE_CEILING["TOOL_RESULT"]
        scopes = ceiling & floor
        if ceiling - floor:
            # Widening across a taint-preserving edge is the laundering case.
            if not dropped:
                raise TaintLaunderingError(
                    f"segment {seg.seg_id!r} role={seg.role} inherits taint "
                    f"{sorted(residual)} via {seg.inputs}; refusing to grant "
                    f"{sorted(ceiling - floor)}"
                )
        return scopes

    return ceiling


def run_trace() -> None:
    graph: dict[str, Segment] = {}

    s1 = Segment("S1", "TOOL_RESULT", frozenset({"untrusted_remote"}))
    graph[s1.seg_id] = s1
    mint(s1, graph)  # ok: {read:scratch}

    # Summarizer segment derived from S1, declared clean by role alone.
    s2 = Segment("S2", "AGENT_INTERNAL", frozenset(), inputs=("S1",))
    graph[s2.seg_id] = s2

    # Naive mint would grant {read:scratch, fs.write, net.post}. Guard fires.
    mint(s2, graph)  # -> raises TaintLaunderingError

    # Legitimate path: typed sanitiser drops taint on a non-payload field only.
    mint(s2, graph, sanitized_fields=[("count", "int")])  # still raises:
    # residual taint persists because the summariser output is free-text.


if __name__ == "__main__":
    run_trace()
