# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-token-whose-delegation-chain-crosses-an-organizational-trust-boundary-mid-task.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-refuse-a-delegated-capability-token-whose-delegation-chain-crosses-an-organizational-trust-boundary-mid-task.warrant.json
# Markdown SHA-256:   abeae23f64bf54ee362e0008baabfbb12f9f575096d9d17e36214af5b9309509
# Code AST SHA-256:   b454a7e294375c2eb7e4e88b0c2beb9ac7c0f5b3abe398925c715913614beffd
# Verified Classes:   DelegationBoundaryError, Caveat, Token, Verifier
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Callable


class DelegationBoundaryError(RuntimeError):
    """Raised when a delegated token carries a caveat the verifier cannot evaluate."""


@dataclass
class Caveat:
    prefix: str          # e.g. "federation", "scope", "aud"
    body: str            # e.g. "within:A"


@dataclass
class Token:
    caveats: list[Caveat]
    delegation_depth: int
    issuer_root: str


@dataclass
class Verifier:
    name: str
    root_of_trust: str
    handlers: dict[str, Callable[[str], bool]] = field(default_factory=dict)
    advisory_prefixes: frozenset[str] = frozenset({"trace", "hint"})
    pinned_vocabulary: frozenset[str] = frozenset()

    def evaluate(self, token: Token) -> bool:
        if token.issuer_root != self.root_of_trust:
            raise DelegationBoundaryError(
                f"{self.name}: untrusted root {token.issuer_root!r}"
            )

        for cav in token.caveats:
            if cav.prefix in self.handlers:
                if not self.handlers[cav.prefix](cav.body):
                    return False
                continue

            # Unknown caveat. Refuse if it is a security-relevant caveat on a
            # delegated token and not in the advisory allowlist.
            if token.delegation_depth >= 1 and cav.prefix not in self.advisory_prefixes:
                raise DelegationBoundaryError(
                    f"{self.name}: cannot evaluate caveat prefix "
                    f"{cav.prefix!r} on delegated token (depth={token.delegation_depth}); "
                    f"pinned_vocabulary={sorted(self.pinned_vocabulary)}; "
                    f"refusing rather than skipping"
                )
            # Root token or advisory caveat: skipping is permitted.
        return True


def authorize_read(verifier: Verifier, token: Token) -> bool:
    """Entry point used by the tool provider before serving a read."""
    if "federation" in verifier.pinned_vocabulary and "federation" not in verifier.handlers:
        # Vocabulary was pinned at federation establishment but no handler was
        # registered: local misconfiguration, not a trust failure.
        raise DelegationBoundaryError(
            f"{verifier.name}: 'federation' is pinned but has no handler; "
            f"deployment is inconsistent"
        )
    return verifier.evaluate(token)


# Reproduction of the observed failure, now refused:
provider = Verifier(
    name="T",
    root_of_trust="A.root",
    handlers={"scope": lambda b: b == "inventory:read", "aud": lambda b: b == "T"},
    pinned_vocabulary=frozenset({"org", "scope", "aud", "delegate", "exp"}),
)

m2 = Token(
    caveats=[
        Caveat("org", "A"),
        Caveat("scope", "inventory:read"),
        Caveat("federation", "within:A"),   # unknown to T, security-relevant
        Caveat("exp", "1750000000"),
        Caveat("delegate", "B"),
        Caveat("delegate", "C"),
    ],
    delegation_depth=2,
    issuer_root="A.root",
)

try:
    authorize_read(provider, m2)
except DelegationBoundaryError as e:
    print(f"REFUSED: {e}")
    # Operator action: reconcile 'federation' handler between A and T,
    # or re-mint under a scope-specific root that T does not trust.
