# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-a-re-issuing-tool-broker-before-a-capability-token-crosses-the-sandbox-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-taint-laundering-through-a-re-issuing-tool-broker-before-a-capability-token-crosses-the-sandbox-boundary.warrant.json
# Markdown SHA-256:   fb68c9e0e8301246190bfb3d433c41e1eae6bdd7295f736509adf40f1e1e3bad
# Code AST SHA-256:   908670e72f29d57345c9ad22cf55637c780b391dfce6bdef71039a465ce10826
# Verified Classes:   TaintLaunderingError, CapabilityToken
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

UNTRUSTED = "UNTRUSTED"
BROKER = "BROKER"
EXEC = "EXEC"

TRUST_ORDER = {UNTRUSTED: 0, EXEC: 1, BROKER: 2}


class TaintLaunderingError(RuntimeError):
    """Raised when a re-issuing tool attempts to broaden a token's
    authority using arguments whose taint would lower the effective
    trust below the requested scope's threshold."""


@dataclass(frozen=True)
class CapabilityToken:
    scope: str
    issuer: str
    lineage: FrozenSet[str] = field(default_factory=frozenset)
    depends_on: FrozenSet[str] = field(default_factory=frozenset)

    @property
    def effective_trust(self) -> str:
        # Meet of the lineage; UNTRUSTED dominates.
        if UNTRUSTED in self.lineage:
            return UNTRUSTED
        return max(self.lineage, key=lambda t: TRUST_ORDER[t]) if self.lineage else UNTRUSTED


def _broadens(new_scope: str, prior_scope: str) -> bool:
    # A scope broadens if it adds reach: wildcard or new sink class.
    if new_scope.endswith(":*") and not prior_scope.endswith(":*"):
        return True
    return new_scope.split(":")[0] != prior_scope.split(":")[0]


def issue_exec_token(
    issuer: str,
    issuer_lineage: FrozenSet[str],
    arg_taint: FrozenSet[str],
    requested_scope: str,
    prior_scope: str,
) -> CapabilityToken:
    lineage = frozenset(issuer_lineage | arg_taint)
    effective = UNTRUSTED if UNTRUSTED in lineage else issuer

    if arg_taint and _broadens(requested_scope, prior_scope):
        raise TaintLaunderingError(
            f"issuer={issuer} attempted to broaden scope "
            f"{prior_scope!r}->{requested_scope!r} under tainted influence "
            f"{sorted(arg_taint)}; effective trust would be {effective}"
        )

    if effective == UNTRUSTED and requested_scope.endswith(":*"):
        raise TaintLaunderingError(
            f"UNTRUSTED-effective token cannot hold wildcard scope {requested_scope!r}"
        )

    return CapabilityToken(
        scope=requested_scope,
        issuer=issuer,
        lineage=lineage,
        depends_on=arg_taint,
    )


def enforce_boundary(token: CapabilityToken, sink_scope: str) -> None:
    if token.effective_trust == UNTRUSTED:
        raise TaintLaunderingError(
            f"token {token.scope!r} from {token.issuer} carries UNTRUSTED lineage "
            f"via {sorted(token.depends_on)}; refusing sink {sink_scope!r}"
        )
