# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-capability-re-derivation-in-tool-sandboxing.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-capability-re-derivation-in-tool-sandboxing.warrant.json
# Markdown SHA-256:   66fb3a23c3b9720717d5fa3bb9f707ea22c8d5aec1743ccf02fa7e21b1a2dce5
# Code AST SHA-256:   f024df6d8bb12af2622816bfa79d9d84b87454ce69fb551737f6f41db5f56686
# Verified Classes:   TaintLaunderingError, Capability, CapabilityLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class TaintLaunderingError(RuntimeError):
    """Raised when a capability is re-derived in a way that drops prior attenuation."""


@dataclass(frozen=True)
class Capability:
    cap_id: str
    tool: str
    taint: FrozenSet[str]
    lineage: FrozenSet[str] = field(default_factory=frozenset)


class CapabilityLedger:
    """Session-scoped record of every attenuation applied to a capability id."""

    def __init__(self) -> None:
        self._attenuated: dict[str, set[str]] = {}

    def record_attenuation(self, cap_id: str, reason: str) -> None:
        self._attenuated.setdefault(cap_id, set()).add(reason)

    def is_attenuated(self, cap_id: str) -> bool:
        return bool(self._attenuated.get(cap_id))


def request_capability(
    descriptor: Capability,
    ledger: CapabilityLedger,
    rederivation_warrant: str | None = None,
) -> Capability:
    """
    Mint a capability handle from a (possibly clean) descriptor.

    Rejects the mint if the descriptor's cap_id was previously attenuated
    in this session and no explicit re-derivation warrant is presented.
    This closes the laundering window where a clean manifest entry is used
    to reconstruct an attenuated capability.
    """
    if ledger.is_attenuated(descriptor.cap_id) and rederivation_warrant is None:
        raise TaintLaunderingError(
            f"capability {descriptor.cap_id!r} for tool {descriptor.tool!r} "
            f"was previously attenuated in this session; re-derivation from a "
            f"clean descriptor would drop attenuation. Provide an audited "
            f"rederivation_warrant or use the original handle."
        )
    # Lineage must be preserved across mint: the new handle is a descendant
    # of the descriptor, and the descriptor's lineage is joined in.
    return Capability(
        cap_id=descriptor.cap_id,
        tool=descriptor.tool,
        taint=descriptor.taint,
        lineage=descriptor.lineage | {descriptor.cap_id},
    )


def invoke(
    handle: Capability,
    attenuated_handle: Capability,
    args_taint: FrozenSet[str],
) -> None:
    """
    Guardrail at invocation: the handle used must be a lineage-descendant of
    any handle that was attenuated for this (tool, principal) pair.
    """
    if not attenuated_handle.lineage.issubset(handle.lineage):
        raise TaintLaunderingError(
            f"handle {handle.cap_id!r} is not a lineage-descendant of the "
            f"attenuated handle {attenuated_handle.cap_id!r}; possible "
            f"capability re-derivation laundering."
        )
    if "UNTRUSTED" in args_taint and "UNTRUSTED" not in handle.taint:
        raise TaintLaunderingError(
            f"tainted arguments routed through clean handle {handle.cap_id!r}."
        )
