# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-capability-token-across-an-org-boundary-and-the-scope-narrowing-check-passes-on-the-wrong-field.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-re-delegates-a-capability-token-across-an-org-boundary-and-the-scope-narrowing-check-passes-on-the-wrong-field.warrant.json
# Markdown SHA-256:   5c1fdc7fb21da0707ada995d7f9d465916a5051ee04a96579ed9e6972d56e137
# Code AST SHA-256:   6e70e612d24ee275fb772e333c9074b0c0c8d0be1549e54f5979db765df0399b
# Verified Classes:   ScopeWideningError, CapabilityToken
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeWideningError(RuntimeError):
    """Raised when a re-delegated token's effective scope exceeds the delegator's."""


@dataclass(frozen=True)
class CapabilityToken:
    issuer: str
    subject: str
    # Authoritative: what the holder can actually exercise.
    effective_scope: FrozenSet[str]
    # Non-authoritative: what was requested. NEVER read by subset checks.
    requested_scope: FrozenSet[str] = field(default_factory=frozenset)
    chain_hash: str = ""


def redelegate(
    parent: CapabilityToken,
    child_subject: str,
    requested: FrozenSet[str],
) -> CapabilityToken:
    # Hard invariant: the child may only request what the parent effectively holds.
    # Checking against parent.requested_scope would reintroduce the widening bug.
    if not requested.issubset(parent.effective_scope):
        widened = requested - parent.effective_scope
        raise ScopeWideningError(
            f"delegation from {parent.subject} to {child_subject} would widen "
            f"effective scope by {sorted(widened)}; "
            f"parent effective={sorted(parent.effective_scope)}"
        )
    child_effective = parent.effective_scope & requested
    return CapabilityToken(
        issuer=parent.subject,
        subject=child_subject,
        effective_scope=child_effective,
        requested_scope=requested,
        chain_hash=f"{parent.chain_hash}:{parent.subject}->{child_subject}",
    )


def authorize(token: CapabilityToken, action: str) -> None:
    # Resource servers authorize on effective_scope ONLY.
    if action not in token.effective_scope:
        raise ScopeWideningError(
            f"action {action!r} not in effective scope of {token.subject}; "
            f"effective={sorted(token.effective_scope)}"
        )
