# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-aaif-capability-token-whose-attestation-chain-re-roots-mid-flight.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-aaif-capability-token-whose-attestation-chain-re-roots-mid-flight.warrant.json
# Markdown SHA-256:   8981a6f02af6625b018530b1acab3aa6adf7ac325b934e686159eb49ab3fcdb0
# Code AST SHA-256:   49668bb180a721c87a89e4c34550f754bd9681bf65cbd1d6939ab1de6b7895b5
# Verified Classes:   AttestationReRootedError, CapabilityToken, AttestationChain
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class AttestationReRootedError(RuntimeError):
    """Raised when a presented attestation chain terminates at an anchor
    outside the capability token's mint-time root_of_trust set."""


@dataclass(frozen=True)
class CapabilityToken:
    subject_leaf_key: str
    root_of_trust: frozenset[str]   # anchors authorized at mint time
    scope: str


@dataclass(frozen=True)
class AttestationChain:
    leaf_key: str
    terminal_anchor: str
    signatures_valid: bool


def authorize_presentation(
    cap: CapabilityToken,
    chain: AttestationChain,
    strict_mode: bool = True,
) -> str:
    # 1. Leaf binding: the chain must attest the key the token was issued to.
    if chain.leaf_key != cap.subject_leaf_key:
        raise AttestationReRootedError(
            f"chain leaf {chain.leaf_key!r} != token subject "
            f"{cap.subject_leaf_key!r}"
        )

    # 2. The token must carry a bound anchor set. Without it, the anchor
    #    cannot be checked, and legacy fallback would launder the anchor.
    if not cap.root_of_trust:
        if strict_mode:
            raise AttestationReRootedError(
                "token has no root_of_trust claim; anchor cannot be bound"
            )
        return "allow_unbound_legacy"

    # 3. Chain must be cryptographically valid.
    if not chain.signatures_valid:
        # Never downgrade to un-attested allow when a root_of_trust exists.
        raise AttestationReRootedError(
            "attestation chain failed signature verification; "
            "refusing legacy un-attested fallback"
        )

    # 4. THE load-bearing invariant: terminal anchor must be a member of the
    #    mint-time anchor set, not merely trusted by the local verifier.
    if chain.terminal_anchor not in cap.root_of_trust:
        raise AttestationReRootedError(
            f"chain re-rooted to {chain.terminal_anchor!r}; "
            f"authorized anchors are {sorted(cap.root_of_trust)}"
        )

    return f"authorized:{cap.scope}"
