# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-trust-chain-re-enters-its-own-issuer-via-a-transitive-delegation-edge.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-trust-chain-re-enters-its-own-issuer-via-a-transitive-delegation-edge.warrant.json
# Markdown SHA-256:   373029b8bcd5df4cde9b6c23dd5950f7dac30c56b38001d8b6d2f4284ba3a1f7
# Code AST SHA-256:   5ee7e597d09ee31a2af3658b4a4e5ec703ad703d6706c02dfe187e1711daa2e6
# Verified Classes:   DelegationReentryError, UntrustedRootError, CapabilityToken
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class DelegationReentryError(RuntimeError):
    """Raised when a delegated capability chain re-enters an issuer already on the path."""
    pass


class UntrustedRootError(RuntimeError):
    """Raised when the chain terminates at an issuer outside the verifier's trust set."""
    pass


@dataclass(frozen=True)
class CapabilityToken:
    token_id: str
    issuer: str
    subject: str
    scopes: frozenset
    parent_id: Optional[str]
    signature_valid: bool


def validate_delegation_chain(
    token: CapabilityToken,
    token_store: dict,
    verifier_issuer: str,
    trusted_roots: frozenset,
) -> list:
    """
    Walk the parent chain from `token` to its root, enforcing:
      1. every signature is valid,
      2. scopes are monotonically attenuated (child ⊆ parent),
      3. no issuer appears twice on the path,
      4. the verifier's own issuer identity appears only at the root,
      5. the root issuer is in the trust set.

    Returns the ordered path [leaf, ..., root].
    Raises DelegationReentryError on issuer re-entry.
    Raises UntrustedRootError if the root is not trusted.
    """
    path = []
    seen_issuers = set()
    current = token
    child_scopes = None

    while current is not None:
        if not current.signature_valid:
            raise DelegationReentryError(
                f"invalid signature on token {current.token_id}"
            )

        # Scope attenuation: child scopes must be a subset of parent scopes.
        if child_scopes is not None and not child_scopes <= current.scopes:
            raise DelegationReentryError(
                f"scope escalation at token {current.token_id}: "
                f"{child_scopes} not subset of {current.scopes}"
            )

        # Re-entry check: the issuer of this hop must not already be on the path.
        if current.issuer in seen_issuers:
            raise DelegationReentryError(
                f"issuer {current.issuer!r} re-enters chain at token "
                f"{current.token_id}; path issuers so far: {sorted(seen_issuers)}"
            )

        # The verifier's own issuer identity must not appear as a non-root issuer.
        if current.issuer == verifier_issuer and current.parent_id is not None:
            raise DelegationReentryError(
                f"verifier issuer {verifier_issuer!r} appears mid-chain at token "
                f"{current.token_id}"
            )

        # The subject of this hop must not be an upstream issuer (the loop edge).
        if current.subject in seen_issuers:
            raise DelegationReentryError(
                f"token {current.token_id} grants authority back to upstream "
                f"issuer {current.subject!r}"
            )

        seen_issuers.add(current.issuer)
        path.append(current)
        child_scopes = current.scopes

        if current.parent_id is None:
            break
        current = token_store.get(current.parent_id)
        if current is None:
            raise DelegationReentryError(
                f"dangling parent reference: {path[-1].parent_id!r} not found"
            )

    root = path[-1]
    if root.issuer not in trusted_roots:
        raise UntrustedRootError(
            f"root issuer {root.issuer!r} not in trust set {sorted(trusted_roots)}"
        )

    return path
