# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-is-a-strict-superset-of-its-own.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-is-a-strict-superset-of-its-own.warrant.json
# Markdown SHA-256:   90b265062147d92d71438e87c19dddf0257f7869db714fb48f2d01e8471fbde0
# Code AST SHA-256:   1ec81fb40383bd8b3762fe3f06dd47c8f550f1aa47441858364f537490ff2dc3
# Verified Classes:   ScopeAmplificationError, ChainIntegrityError, Link
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass


class ScopeAmplificationError(RuntimeError):
    """Raised when a delegation link widens scope relative to its parent."""
    pass


class ChainIntegrityError(RuntimeError):
    pass


@dataclass(frozen=True)
class Link:
    issuer: str
    scope: frozenset  # normalized, wildcards already resolved to finite sets


def effective_scope(chain: list, envelope: frozenset, registry: dict) -> frozenset:
    if not chain:
        raise ChainIntegrityError("empty delegation chain")
    for link in chain:
        if link.scope is None:
            raise ChainIntegrityError(f"link {link.issuer} omits scope")

    clamped = chain[0].scope
    for parent, child in zip(chain, chain[1:]):
        # monotone-decreasing invariant: child must be subset of parent
        widened = child.scope - parent.scope
        if widened:
            raise ScopeAmplificationError(
                f"link {child.issuer} widens scope beyond parent {parent.issuer}: "
                f"{sorted(widened)}"
            )
        clamped = clamped & child.scope

    # wildcard in leaf that resolves against registry is intersected, never expanded
    resolved = frozenset(
        r for r in clamped if r != "*" or r in registry
    )
    return resolved & envelope


def authorize(chain: list, envelope: frozenset, registry: dict, requested: str) -> bool:
    scope = effective_scope(chain, envelope, registry)
    if requested not in scope:
        return False
    return True
