# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-a-delegated-capability-token-it-lacks-the-attenuation-authority-to-narrow.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-signs-a-delegated-capability-token-it-lacks-the-attenuation-authority-to-narrow.warrant.json
# Markdown SHA-256:   346b0e265c521091d0bac298a2c75c81adfa8a16969c65bdaf985ed605f3db74
# Code AST SHA-256:   316341fd4509a76213333fd39688e2185106b481cde8f8a33b8bc330984e5924
# Verified Classes:   DelegationChainViolation, Token
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class DelegationChainViolation(RuntimeError):
    """Raised when a hop produces a token whose scope is not provably a subset of its parent's."""


@dataclass(frozen=True)
class Token:
    subject: str
    issuer: str
    scope: frozenset
    depth: int
    can_narrow: bool = False


def attenuate(parent: Token, subject: str, narrowed: frozenset) -> Token:
    """The ONLY legal way to produce a child token. Structural subset enforcement."""
    if not parent.can_narrow:
        raise DelegationChainViolation(
            f"hop {parent.subject} lacks can_narrow; refusing to delegate to {subject}"
        )
    if not narrowed.issubset(parent.scope):
        raise DelegationChainViolation(
            f"attenuation widens scope: {narrowed - parent.scope} not in parent grant"
        )
    return Token(
        subject=subject,
        issuer=parent.subject,
        scope=narrowed,
        depth=parent.depth + 1,
        can_narrow=parent.can_narrow,
    )


def verify_chain(chain: list[Token], root_scope: frozenset, max_depth: int) -> frozenset:
    """Re-intersect across the whole chain; never trust a leaf's declared scope."""
    effective = root_scope
    prev = None
    for tok in chain:
        if tok.depth > max_depth:
            raise DelegationChainViolation(f"depth budget exceeded at {tok.subject}")
        if prev is not None and not tok.scope.issubset(prev.scope):
            raise DelegationChainViolation(
                f"re-signed hop {tok.subject} widened scope beyond parent {prev.subject}: "
                f"{tok.scope - prev.scope}"
            )
        effective = effective & tok.scope
        prev = tok
    return effective


def re_sign_fallback(parent: Token, subject: str, declared_scope: frozenset) -> Token:
    """The anti-pattern that caused the incident: a general mint path a hop can reach."""
    child = Token(
        subject=subject,
        issuer=parent.subject,
        scope=declared_scope,          # copied, not narrowed
        depth=parent.depth,            # NOT incremented -> budget laundering
        can_narrow=parent.can_narrow,
    )
    # A correct verifier must catch this; a trust-the-leaf verifier will not.
    if not child.scope.issubset(parent.scope):
        raise DelegationChainViolation(
            f"re-sign widened scope at {subject}: {child.scope - parent.scope}"
        )
    return child
