# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-an-over-scoped-delegated-credential-when-the-cross-issuer-trust-chain-validates-but-the-scope-intersection-is-empty.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-an-over-scoped-delegated-credential-when-the-cross-issuer-trust-chain-validates-but-the-scope-intersection-is-empty.warrant.json
# Markdown SHA-256:   18e226707ce94c20f0d0d5d5bc0cb96a2709e2e96f155b65b4cb42f0d5e9cd72
# Code AST SHA-256:   4fe3798746d0acce6ad87f150a13567cda5823a75a5aad40406bf7477d9762cd
# Verified Classes:   OverScopedDelegationError, Hop, Credential
# Defensive Guards:   6 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Iterable

class OverScopedDelegationError(RuntimeError):
    """Raised when a delegated credential's terminal scope names a namespace
    whose authoritative issuer set does not include the hop that introduced it."""


@dataclass(frozen=True)
class Hop:
    issuer: str
    audience: str
    scope: frozenset[str]
    introduced: frozenset[str]  # scope elements first appearing at this hop


@dataclass(frozen=True)
class Credential:
    chain: tuple[Hop, ...]
    terminal_issuer: str


def verify_delegated_credential(
    cred: Credential,
    namespace_authority: dict[str, set[str]],
    trusted_issuers: Iterable[str],
) -> frozenset[str]:
    trusted = set(trusted_issuers)

    # Phase 1: chain validity (signatures/aud/exp assumed pre-checked upstream).
    for i, hop in enumerate(cred.chain):
        if hop.issuer not in trusted:
            raise OverScopedDelegationError(
                f"hop {i} issuer {hop.issuer!r} not in trusted set"
            )
        if i > 0 and hop.issuer != cred.chain[i - 1].audience:
            raise OverScopedDelegationError(
                f"hop {i} issuer {hop.issuer!r} does not match prior audience"
            )

    # Phase 2: scope subsetting (lattice meet).
    effective = cred.chain[-1].scope
    for i, hop in enumerate(cred.chain):
        if not effective <= hop.scope:
            raise OverScopedDelegationError(
                f"terminal scope not subset of hop {i} scope"
            )

    # Phase 3: per-namespace authority partition check.
    # Provenance: which hop first introduced each scope element.
    provenance: dict[str, str] = {}
    for hop in cred.chain:
        for elem in hop.introduced:
            provenance.setdefault(elem, hop.issuer)

    for elem in effective:
        namespace = elem.split(":", 1)[0]
        introducer = provenance.get(elem)
        if introducer is None:
            raise OverScopedDelegationError(
                f"scope element {elem!r} has no recorded provenance"
            )
        authoritative = namespace_authority.get(namespace)
        if authoritative is None:
            # Fail closed: unknown namespace, no authority registry entry.
            raise OverScopedDelegationError(
                f"namespace {namespace!r} has no authority registry entry"
            )
        if introducer not in authoritative:
            raise OverScopedDelegationError(
                f"scope element {elem!r} introduced by {introducer!r}, "
                f"which is not authoritative for namespace {namespace!r} "
                f"(authoritative: {sorted(authoritative)})"
            )

    return effective


# Replay of the observed failure shape:
chain = (
    Hop(issuer="A",  audience="B",  scope=frozenset({"files:read", "billing:charge"}),
        introduced=frozenset({"files:read", "billing:charge"})),
    Hop(issuer="B2", audience="C",  scope=frozenset({"billing:charge"}),
        introduced=frozenset()),
)
cred = Credential(chain=chain, terminal_issuer="B2")
authority = {"billing": {"A"}, "files": {"A"}}

try:
    verify_delegated_credential(cred, authority, trusted_issuers={"A", "B2"})
except OverScopedDelegationError as e:
    print("REJECTED (correct):", e)
