# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-attestation-chain-scope-widening-during-cross-org-trust-federation.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-attestation-chain-scope-widening-during-cross-org-trust-federation.warrant.json
# Markdown SHA-256:   f96e7fd29abd78b3d14d3a5a56a8e8cbce042a8eaaa75e2131b981a07dae906d
# Code AST SHA-256:   dcc58ff99d621eadf4cd24fe25e14fefe5f6bf95ce01355d48d350fec00f23f3
# Verified Classes:   ScopeWideningError, Hop
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Mapping


class ScopeWideningError(RuntimeError):
    """Raised when a delegation chain confers authority absent from an ancestor grant."""


@dataclass(frozen=True)
class Hop:
    issuer: str
    subject: str
    caps: frozenset[str]          # already translated into verifier-local vocabulary
    delegated_ceiling: frozenset[str] | None  # None => boolean delegate flag (unsound)


def verify_chain(
    chain: list[Hop],
    requested: frozenset[str],
    pinned_root_caps: Mapping[str, frozenset[str]],
) -> frozenset[str]:
    if not chain:
        raise ScopeWideningError("empty chain")

    root = chain[0]
    if root.issuer not in pinned_root_caps:
        raise ScopeWideningError(
            f"root issuer {root.issuer!r} has no locally pinned grant; "
            "trust-on-first-attestation cannot enforce scope intersection"
        )

    # The root's authority is its pinned grant, not its self-asserted caps.
    effective = pinned_root_caps[root.issuer] & root.caps

    for i, hop in enumerate(chain[1:], start=1):
        if hop.delegated_ceiling is None:
            raise ScopeWideningError(
                f"hop {i} ({hop.issuer}->{hop.subject}) uses a boolean delegate flag; "
                "delegation ceiling is unbounded"
            )
        # A hop may only confer a subset of what its issuer actually held.
        if not hop.caps <= effective:
            widened = hop.caps - effective
            raise ScopeWideningError(
                f"scope widening at hop {i} ({hop.issuer}->{hop.subject}): "
                f"confers {sorted(widened)} not held by issuer"
            )
        if not hop.delegated_ceiling <= effective:
            raise ScopeWideningError(
                f"hop {i} delegation ceiling exceeds issuer authority: "
                f"{sorted(hop.delegated_ceiling - effective)}"
            )
        effective = effective & hop.caps

    if not requested <= effective:
        raise ScopeWideningError(
            f"requested {sorted(requested - effective)} not covered by "
            f"intersected chain scope {sorted(effective)}"
        )
    return effective
