# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-cross-org-federation-from-silently-widening-trust-scope-during-capability-re-negotiation.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-cross-org-federation-from-silently-widening-trust-scope-during-capability-re-negotiation.warrant.json
# Markdown SHA-256:   26608cda6bf94f45f5f6f9bfcace7d2294237db8b5be69beb4120ade517e5bfe
# Code AST SHA-256:   9814d8718ad2e0a44926f156c925713461294bd2bacf7ffd07df2ff4772be02c
# Verified Classes:   TrustScopeEscalation, Warrant, Grant
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet

class TrustScopeEscalation(RuntimeError):
    """Raised when a re-negotiated grant exceeds the originating warrant's scope."""
    pass

@dataclass(frozen=True)
class Warrant:
    root_id: str
    scope: FrozenSet[str]

@dataclass(frozen=True)
class Grant:
    issuer: str
    chain: tuple  # (Warrant, Grant, Grant, ...) root-first

    @property
    def root(self) -> Warrant:
        return self.chain[0]

def issue_grant(
    parent: Grant,
    issuer_policy: FrozenSet[str],
    requested: FrozenSet[str],
    issuer_id: str,
) -> Grant:
    # Re-derive from the ROOT warrant, not the immediate parent.
    effective = parent.root.scope & issuer_policy
    for link in parent.chain[1:]:
        effective &= link.issuer_scope  # each hop may only narrow
    if not requested <= effective:
        raise TrustScopeEscalation(
            f"issuer={issuer_id} requested={sorted(requested)} "
            f"exceeds root={parent.root.root_id} "
            f"effective={sorted(effective)}; "
            f"leaf-relative check would have passed but root forbids it"
        )
    narrowed = Grant(issuer=issuer_id, chain=parent.chain + (parent,))
    object.__setattr__(narrowed, "issuer_scope", requested)  # frozen workaround
    return narrowed

def verify_grant(grant: Grant, auditor_policy: FrozenSet[str]) -> bool:
    # Auditor MUST re-derive from root independently of issuance path.
    effective = grant.root.scope & auditor_policy
    for link in grant.chain[1:]:
        effective &= link.issuer_scope
    leaf = grant.chain[-1].issuer_scope
    if not leaf <= effective:
        raise TrustScopeEscalation(
            f"auditor replay: leaf={sorted(leaf)} not derivable from "
            f"root={grant.root.root_id}; verification would be correlated "
            f"with the issuance bug if checked leaf-relative"
        )
    return True
