# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-capability-grant-as-invalid-the-moment-any-intermediate-policy-negotiation-hop-re-signs-the-capab.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-federated-capability-grant-as-invalid-the-moment-any-intermediate-policy-negotiation-hop-re-signs-the-capab.warrant.json
# Markdown SHA-256:   b2ba516522d67e96d1ed7ff6560b012155f922983abc3f99429fe1c42271b6a0
# Code AST SHA-256:   7791571f91d86e4192b9ff2574d6395f704543dff629dd15e758a49968efa7ef
# Verified Classes:   WidenedCapabilityError, Hop, Envelope
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class WidenedCapabilityError(RuntimeError):
    """Raised when a federated capability chain widens scope at any hop."""


@dataclass
class Hop:
    signer: str
    scope: frozenset[str]
    constraints: frozenset[str]
    is_origin: bool


@dataclass
class Envelope:
    hops: list[Hop] = field(default_factory=list)


def verify_chain(envelope: Envelope, origin_authority: str) -> frozenset[str]:
    """Return effective scope = intersection of all hops, or raise on widening.

    Rejects: non-monotone narrowing, constraint drops, and chains whose
    terminal signer is not the origin when the origin is not present.
    """
    if not envelope.hops:
        raise WidenedCapabilityError("empty capability chain")

    origin_hop: Optional[Hop] = None
    for hop in envelope.hops:
        if hop.is_origin:
            if hop.signer != origin_authority:
                raise WidenedCapabilityError(
                    f"origin hop signed by {hop.signer!r}, "
                    f"expected authority {origin_authority!r}"
                )
            origin_hop = hop
            break

    if origin_hop is None:
        raise WidenedCapabilityError(
            "no origin hop in chain: envelope is unverified re-attestation"
        )

    effective = origin_hop.scope
    effective_constraints = origin_hop.constraints

    for hop in envelope.hops[envelope.hops.index(origin_hop) + 1:]:
        if not hop.scope.issubset(effective):
            raise WidenedCapabilityError(
                f"hop signed by {hop.signer!r} widens scope: "
                f"{sorted(hop.scope - effective)} not granted by parent"
            )
        if hop.constraints < effective_constraints:
            dropped = effective_constraints - hop.constraints
            raise WidenedCapabilityError(
                f"hop signed by {hop.signer!r} drops constraints {sorted(dropped)}"
            )
        effective = hop.scope
        effective_constraints = hop.constraints

    return effective


# Trace from the observed incident: Org B's broker widened op and dropped no_export.
incident = Envelope(hops=[
    Hop(signer="A", scope=frozenset({"read"}),
        constraints=frozenset({"no_export", "eu-west"}), is_origin=True),
    Hop(signer="B", scope=frozenset({"read", "list", "describe"}),
        constraints=frozenset(), is_origin=False),
])

try:
    verify_chain(incident, origin_authority="A")
except WidenedCapabilityError as e:
    print(f"REJECTED at consumer: {e}")
