# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-capabilities-across-federated-trust-boundaries-and-its-policy-engine-silently-widens-scope-mid-session.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-negotiates-capabilities-across-federated-trust-boundaries-and-its-policy-engine-silently-widens-scope-mid-session.warrant.json
# Markdown SHA-256:   f3a24d0d1d23aaf0c07863bad9e110be9148603732d4ce1ed4c0fded03cb6fb7
# Code AST SHA-256:   9ba73be0869fc2d66113a724509691ca76087581f379b4ae4c439f71ed767e43
# Verified Classes:   CapabilityWideningError, Grant, Session
# Defensive Guards:   1 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class CapabilityWideningError(RuntimeError):
    """Raised when a re-negotiated grant exceeds the session-original grant
    without an accompanying policy-authority re-authorization token."""


@dataclass
class Grant:
    scopes: FrozenSet[str]
    reauth_token: str | None = None


@dataclass
class Session:
    session_id: str
    original_granted: FrozenSet[str]
    current_granted: FrozenSet[str] = field(default_factory=frozenset)

    def __post_init__(self) -> None:
        self.current_granted = self.original_granted


def adopt_renegotiated_grant(session: Session, incoming: Grant) -> FrozenSet[str]:
    """
    Adopt a re-negotiated grant under the restate-or-narrow invariant.

    A re-negotiation may restate or narrow the session-original grant. It may
    not widen it unless the incoming grant carries a re-authorization token
    issued by the consumer's policy authority.
    """
    widened = incoming.scopes - session.original_granted

    if widened and incoming.reauth_token is None:
        # Neutralize the widening: intersect with the session baseline.
        # The excess scopes are dropped, not admitted.
        admitted = incoming.scopes & session.original_granted
        session.current_granted = admitted
        raise CapabilityWideningError(
            f"session={session.session_id} re-negotiation attempted to widen "
            f"grant by {sorted(widened)} without reauth_token; "
            f"excess scopes dropped, admitted={sorted(admitted)}"
        )

    if widened and incoming.reauth_token is not None:
        # Out-of-band authorization: adopt wholesale, but record the delta.
        session.current_granted = incoming.scopes
        return incoming.scopes

    # Restate-or-narrow: safe to adopt.
    session.current_granted = incoming.scopes
    return incoming.scopes


def admit_message(session: Session, msg_scope: str) -> bool:
    if msg_scope not in session.current_granted:
        return False
    # Defense in depth: never admit beyond the session baseline, even if
    # current_granted was corrupted by an upstream bug.
    return msg_scope in session.original_granted or session.current_granted <= session.original_granted
