# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-verify-a-federated-capability-grant-after-a-policy-renegotiation-that-silently-widened-scope.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-verify-a-federated-capability-grant-after-a-policy-renegotiation-that-silently-widened-scope.warrant.json
# Markdown SHA-256:   25c0855198d701f339bfb5f3753215d1a8f57c9007fbf37a3d6b1e0c8e7dc5f2
# Code AST SHA-256:   60d5ddca461df56a6a26a25f604e86c2ce1831eb940545119d5dd27f56e20a51
# Verified Classes:   ScopeBoundaryViolation, Envelope, AuthorizationRecord, FederatedBroker
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeBoundaryViolation(RuntimeError):
    """Raised when a renegotiated envelope exceeds the broker's authorized scope."""
    pass


@dataclass(frozen=True)
class Envelope:
    envelope_id: str
    scope: FrozenSet[str]
    signer_org: str
    signature_valid: bool


@dataclass
class AuthorizationRecord:
    task_id: str
    version: int
    authorized_scope: FrozenSet[str]
    # Append-only: new versions are added, never mutate prior entries.


class FederatedBroker:
    def __init__(self) -> None:
        self._auth_records: dict[str, list[AuthorizationRecord]] = {}

    def authorize(self, task_id: str, scope: FrozenSet[str]) -> AuthorizationRecord:
        versions = self._auth_records.setdefault(task_id, [])
        rec = AuthorizationRecord(task_id=task_id, version=len(versions) + 1,
                                  authorized_scope=scope)
        versions.append(rec)
        return rec

    def current_auth(self, task_id: str) -> AuthorizationRecord:
        return self._auth_records[task_id][-1]

    def gate_envelope(self, task_id: str, envelope: Envelope) -> None:
        """Gate every envelope transition, including renegotiation, against
        the broker's OWN authorization record -- not the previous envelope."""
        if not envelope.signature_valid:
            raise ScopeBoundaryViolation(
                f"envelope {envelope.envelope_id} signature invalid"
            )
        auth = self.current_auth(task_id)
        excess = envelope.scope - auth.authorized_scope
        if excess:
            # Do NOT compare against previous envelope; compare against auth.
            raise ScopeBoundaryViolation(
                f"envelope {envelope.envelope_id} (signer={envelope.signer_org}) "
                f"requests scope outside authorization v{auth.version} for task "
                f"{task_id}: {sorted(excess)}. Renegotiation cannot widen scope "
                f"without explicit re-authorization."
            )

    def renegotiate_and_route(self, task_id: str, counter: Envelope) -> Envelope:
        # The counter is fully valid and correctly signed by the provider.
        # It is still rejected if it widens scope beyond the auth record.
        self.gate_envelope(task_id, counter)
        return counter


def demo() -> None:
    broker = FederatedBroker()
    broker.authorize("T-1", frozenset({"read:d-4417", "compute:summarize"}))
    # Provider counter-proposal: valid signature, but bundles extra clauses.
    counter = Envelope(
        envelope_id="E1",
        scope=frozenset({"read:d-4417", "read:d-4418",
                         "compute:summarize", "compute:export"}),
        signer_org="org-B",
        signature_valid=True,
    )
    broker.renegotiate_and_route("T-1", counter)  # raises


if __name__ == "__main__":
    demo()
