# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-warrant-after-identity-bridging-silently-widens-its-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-federated-capability-warrant-after-identity-bridging-silently-widens-its-scope.warrant.json
# Markdown SHA-256:   537ea873a2324c8bd8d4750ed689226d981de7793b2255f11417dc3ab5c4be09
# Code AST SHA-256:   d95fcdddda33174d7924173d23ea0327b1ca12f18515595d6ae5aeaee1301a36
# Verified Classes:   FederatedScopeWideningError, ScopeAtom, Warrant
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import FrozenSet


class FederatedScopeWideningError(RuntimeError):
    """Raised when a bridged capability warrant grants more scope than was requested."""


@dataclass(frozen=True)
class ScopeAtom:
    action: str
    resource: str  # may contain a trailing '*' glob


@dataclass(frozen=True)
class Warrant:
    issuer: str
    subject: str          # bridged guest principal
    requested_scope: FrozenSet[ScopeAtom]  # S_req, embedded request digest
    effective_scope: FrozenSet[ScopeAtom]  # S_eff, what broker minted
    attenuated_from: str  # original caller principal, or "" if unbound
    signature_valid: bool


def _atom_subsumes(broad: ScopeAtom, narrow: ScopeAtom) -> bool:
    if broad.action != narrow.action:
        return False
    if broad.resource == narrow.resource:
        return True
    if broad.resource.endswith("*"):
        return narrow.resource.startswith(broad.resource[:-1])
    return False


def _scope_subset(sub: FrozenSet[ScopeAtom], sup: FrozenSet[ScopeAtom]) -> bool:
    return all(any(_atom_subsumes(s, a) for s in sup) for a in sub)


def accept_federated_warrant(w: Warrant, caller_principal: str) -> None:
    if not w.signature_valid:
        raise FederatedScopeWideningError("signature invalid; reject before scope checks")

    # Invariant 1: effective scope must be a subset of requested scope.
    if not _scope_subset(w.effective_scope, w.requested_scope):
        widened = w.effective_scope - w.requested_scope
        raise FederatedScopeWideningError(
            f"scope widened across identity bridge: requested={sorted(map(str, w.requested_scope))} "
            f"effective={sorted(map(str, w.effective_scope))} delta={sorted(map(str, widened))}"
        )

    # Invariant 2: the bridge must bind the original caller principal.
    if w.attenuated_from != caller_principal:
        raise FederatedScopeWideningError(
            f"unbound bridge: warrant attenuated_from={w.attenuated_from!r} "
            f"but caller is {caller_principal!r}; guest subject={w.subject!r} is not provenance-bound"
        )


# Failing case: broker widened read:dataset/quarterly -> read:dataset/* via glob intersection.
warrant = Warrant(
    issuer="broker:federation",
    subject="guest:beta/role:analyst",
    requested_scope=frozenset({ScopeAtom("read", "dataset/quarterly")}),
    effective_scope=frozenset({ScopeAtom("read", "dataset/*")}),
    attenuated_from="agent:acme/planner",
    signature_valid=True,
)
accept_federated_warrant(warrant, caller_principal="agent:acme/planner")
