# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-was-widened-by-a-downstream-re-delegation-chain-rather-than-its-own-issuer.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-credential-whose-scope-was-widened-by-a-downstream-re-delegation-chain-rather-than-its-own-issuer.warrant.json
# Markdown SHA-256:   8f6b9fdaafdba965711c06524e67eaacb88eab4777c0b9626871bfbf8e4eef55
# Code AST SHA-256:   e12fb3be9d705b173c290ec6734585c8beaa7f21d11c6ba131631aecc8513218
# Verified Classes:   ChainScopeEscalation, Hop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class ChainScopeEscalation(RuntimeError):
    """Raised when a delegated token's scope exceeds the upstream intersection."""
    pass


@dataclass(frozen=True)
class Hop:
    issuer: str
    subject: str
    scope: FrozenSet[str]
    signature_valid: bool


def verify_chain_bound_scope(chain: list[Hop], requested: FrozenSet[str]) -> FrozenSet[str]:
    """
    chain[0] is the root grant; chain[-1] is the leaf token presented to us.
    Returns the effective scope if and only if the leaf scope is a subset of
    the intersection of all upstream scopes AND the requested scope is a
    subset of the leaf scope. Otherwise raises.
    """
    if not chain:
        raise ChainScopeEscalation("empty delegation chain")

    for i, hop in enumerate(chain):
        if not hop.signature_valid:
            raise ChainScopeEscalation(f"hop {i} ({hop.issuer}->{hop.subject}) signature invalid")

    # The invariant: effective scope is the intersection across every hop.
    effective = chain[0].scope
    for hop in chain[1:]:
        effective = effective & hop.scope

    leaf = chain[-1]

    # A leaf that carries scope outside the upstream intersection is a
    # widened (escalated) token, even though its own signature is valid.
    widened = leaf.scope - effective
    if widened:
        raise ChainScopeEscalation(
            f"leaf scope widened beyond upstream intersection: {sorted(widened)}"
        )

    if not requested <= leaf.scope:
        raise ChainScopeEscalation(
            f"requested {sorted(requested)} not covered by leaf scope {sorted(leaf.scope)}"
        )

    return effective & requested


# Example: A->B grants {read:kb, write:scratch}; B->C widens to include read:secrets.
chain = [
    Hop("A", "B", frozenset({"read:kb", "write:scratch"}), True),
    Hop("B", "C", frozenset({"read:kb", "write:scratch", "read:secrets"}), True),
]

try:
    verify_chain_bound_scope(chain, frozenset({"read:secrets"}))
except ChainScopeEscalation as e:
    # Correct behavior: refuse, do not downgrade and retry.
    print(f"REJECTED: {e}")
