# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-capability-attestation-whose-scope-was-widened-by-a-downstream-peer-transitive-scope-inflati.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-reject-a-federated-capability-attestation-whose-scope-was-widened-by-a-downstream-peer-transitive-scope-inflati.warrant.json
# Markdown SHA-256:   f2276952c0ca6e271a0134e3157e10ce62e3b2b95b1eb00a6ebb4572c23facf5
# Code AST SHA-256:   97014b9c46888a26878a39387c833a1eec411899393f4333c963639e1b3f8d27
# Verified Classes:   ScopeInflationError, Hop, Attestation
# Defensive Guards:   7 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class ScopeInflationError(RuntimeError):
    """Raised when a federated attestation delivers a scope that is not a
    subset of every upstream hop's signed scope, or of the requester's own
    requested scope. Indicates transitive authority widening."""


@dataclass
class Hop:
    issuer: str
    scope: frozenset          # signed scope claim at this hop
    signature_valid: bool


@dataclass
class Attestation:
    hops: list[Hop]           # ordered root -> ... -> delivering peer
    delivered_scope: frozenset
    requested_scope: frozenset
    evidence_complete: bool = True


def scope_subset(inner: frozenset, outer: frozenset) -> bool:
    # Wildcards are represented as the literal "*" element; "*" in inner
    # but not in outer is a widening, never a subset.
    if "*" in inner and "*" not in outer:
        return False
    return inner.issubset(outer)


def verify_federated_attestation(att: Attestation) -> frozenset:
    if not att.evidence_complete or not att.hops:
        raise ScopeInflationError(
            "attestation evidence bundle incomplete; cannot evaluate scope monotonicity"
        )

    # 1. Every hop signature must be valid (necessary, not sufficient).
    for hop in att.hops:
        if not hop.signature_valid:
            raise ScopeInflationError(f"invalid signature at hop {hop.issuer}")

    # 2. Delivered scope must not exceed the requester's own request.
    if not scope_subset(att.delivered_scope, att.requested_scope):
        raise ScopeInflationError(
            f"delivered scope {sorted(att.delivered_scope)} widens requester scope "
            f"{sorted(att.requested_scope)}"
        )

    # 3. Scope monotonicity across every consecutive hop: next ⊆ prev.
    for prev, nxt in zip(att.hops, att.hops[1:]):
        if not scope_subset(nxt.scope, prev.scope):
            raise ScopeInflationError(
                f"scope widened from {prev.issuer} {sorted(prev.scope)} "
                f"to {nxt.issuer} {sorted(nxt.scope)}"
            )

    # 4. Delivered scope must be a subset of the terminal hop's signed scope.
    if not scope_subset(att.delivered_scope, att.hops[-1].scope):
        raise ScopeInflationError(
            "delivered scope exceeds terminal hop signed scope"
        )

    # 5. Effective authority is the intersection of all constraints.
    effective = att.delivered_scope & att.requested_scope
    for hop in att.hops:
        effective &= hop.scope
    if not effective:
        raise ScopeInflationError("empty effective scope after intersection; fail closed")
    return effective


def handle_inbound_attestation(att: Attestation) -> frozenset:
    try:
        return verify_federated_attestation(att)
    except ScopeInflationError:
        # Fail closed: do not downgrade silently, do not execute.
        raise
